close

[Solved] java.lang.NullPointerException: Cannot invoke method get() on null object

Hello Guys, How are you all? Hope You all Are Fine. Today I am facing the following error java.lang.NullPointerException: Cannot invoke method get() on null object in Java. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How java.lang.NullPointerException: Cannot invoke method get() on null object Error Occurs?

Today I am facing the following error java.lang.NullPointerException: Cannot invoke method get() on null object in Java.

How To Solve java.lang.NullPointerException: Cannot invoke method get() on null object Error ?

  1. How To Solve java.lang.NullPointerException: Cannot invoke method get() on null object Error ?

    To Solve java.lang.NullPointerException: Cannot invoke method get() on null object Error object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it.

  2. java.lang.NullPointerException: Cannot invoke method get() on null object

    To Solve java.lang.NullPointerException: Cannot invoke method get() on null object Error object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it.

Solution 1

object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.

Solution 2

Handle the null issue inside your code as follows (Use null safe operator and groovy truth concept.)

@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')

import static groovyx.net.http.HttpBuilder.configure
def astros = configure {
    request.uri = 'http://api.open-notify.org/astros.json'
}?.get() // added null safe operator here (will handle null pointer exception)

println "There are ${astros?.number} astronauts in space right now."
//iterate if astros value exists.
if(astros){
  astros.people.each { p->
    println " - ${p.name} (${p.craft})"
  }
}

// As you are having json, you need to parse that as follows.

  def slurper = new groovy.json.JsonSlurper()
  def result = slurper.parseText(astros)
  println result
  println result?.number

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read