15

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.

mertaydin
  • 2,184
  • 5
  • 19
  • 26

3 Answers3

43

Assuming that object is of type JSONObject you can use

object.optInt(Constants.FirmID)

or

object.optInt(Constants.FirmID, defaultValue)
Henry
  • 42,982
  • 7
  • 68
  • 84
-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

Community
  • 1
  • 1
Lalith B
  • 11,843
  • 6
  • 29
  • 47
  • 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. – mertaydin Dec 28 '12 at 09:57
  • 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 ? – Lalith B Dec 28 '12 at 10:02
-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 . . . . . 
    }
VIGNESH
  • 2,023
  • 8
  • 31
  • 46