17

I'm trying to get values from Json object and I have a problem. I'm using getint function to get value but the value is null and getint function gving error.

How can I solve this problem?

Code :

firmInfo.setFirmID(object.getInt(Constants.FirmID));

Thanks.

3 Answers 3

46

Assuming that object is of type JSONObject you can use

object.optInt(Constants.FirmID)

or

object.optInt(Constants.FirmID, defaultValue)
Sign up to request clarification or add additional context in comments.

Comments

-1

You can check if the object you recieve is an instanceof JSONObject before you try to getInt(). Also you need to check if null before passing as a param to your getInt(). Like below

if(Constants.FirmID != null){
 firmInfo.setFirmID(object.getInt(Integer.parseInt(Constants.FirmID)));
}

Check this link

2 Comments

No no no, Constants.FirmID isn't already null. getInt(Constants.FirmID) is getting value from Jsononject and the variable is FirmID. { FirmID :null } like this.
ooh ok so the JSON object for FirmID is null ?, In that case you cannot getInt of null. Its a server side issue/bug. If you think the object firmid should contain integers fix the server to send you 0 instead of null ?
-2

getint gives error message if there is no such key in JSONObject or your error is while setting it to firmInfo

check whether the id is present or not using

object.has("Constants.FirmID")

if it has the key , check whether it is null or not

if(String.valueOf(jArray.getInt("sdfgh")) != null)
{
    // add your code here . . . . . 
}

or

if(String.valueOf(jArray.getInt("sdfgh")).length < 1)
    {
        // add your code here . . . . . 
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.