24

I have a function which saves Android data in sqlite but I have to convert the String data to an Integer.

Whenever the String is null i would like to save as 0

The following is my code which fails whenever the value is null

 int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));

The block_id above is converted to an Integer.

This is what i have decided to do but still it fails to convert the string value to 0 whenever its null.

int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));

Then the function convertToInt

 public static Integer convertToInt(String str) {
    int n=0;
  if(str != null) {
      n = Integer.parseInt(str);
  }
    return n;
}

How should I change it, to make it work?

5
  • 4
    Please post a minimal reproducible example. I suspect your String isn't null but empty. Commented Sep 27, 2016 at 14:04
  • 4
    That code looks like it should work, although I'd return int instead of Integer, and change your method name to convertToInt (or parseIntOrNull) Commented Sep 27, 2016 at 14:05
  • After you checked if the string isnt't null I would also check if the string only contains numbers: str.matches("[0-9]+");. Or you simply catch the parse exception. Commented Sep 27, 2016 at 14:08
  • JSONObject jObj = jsonarray.getJSONObject(i); int block_id = TextUtils.isEmpty(jObj.getString("block_id"))?0:jObj.getInt("block_id") ; Try this Commented Oct 12, 2016 at 9:38
  • Checkout my one-line code answer: stackoverflow.com/a/77739302/4621922 Commented Dec 31, 2023 at 17:34

12 Answers 12

24
+100

Simply use the built-in method JSONObject#getInt(String), it will automatically convert the value to an int by calling behind the scene Integer.parseInt(String) if it is a String or by calling Number#intValue() if it is a Number. To avoid an exception when your key is not available, simply check first if your JSONObject instance has your key using JSONObject#has(String), this is enough to be safe because a key cannot have a null value, either it exists with a non null value or it doesn't exist.

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
Sign up to request clarification or add additional context in comments.

Comments

16

Instead of writing your own function use the inbuild construction of try-catch. Your problem is, that jsonarray or jsonarray.getJSONObject(i) or the value itself is a null and you call a method on null reference. Try the following:

int block_id = 0;        //this set's the block_id to 0 as a default.
try {
    block_id =  Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));    //this will set block_id to the String value, but if it's not convertable, will leave it 0.
} catch (Exception e) {};

In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.

try{
    //some code
} catch (NumberFormatException e1) {
    e.printStackTrace()     //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
    e.printStackTrace();
}

or using the fact, that they all extend Exception:

try {
    //somecode
} catch (Exception e) {
    e.printStackTrace;
};

or since Java 7:

try {
    //somecode
} catch (NullPointerException | NumberFormatException e) {
    e.printStackTrace;
};

Note

As I believe, that you'll read the answer carefully, please have in mind, that on StackOverflow we require the Minimal, Complete, and Verifiable example which include the StackTrace of your exception. In your case it probably starts with the following:

Exception in thread "main" java.lang.NullPointerException

Then, debugging is much easier. Without it, it's just guessing.

Edit: According to the accepted answer

The accepted answer is good and will work as long, as the value stored with key: block_id will be numeric. In case it's not numeric, your application will crash.

Instead of:

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

One should use:

int block_id;
try{
    JSONObject jObj = jsonarray.getJSONObject(i);
    block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
} catch (JSONException | NullPointerException e) {
    e.printStackTrace();
}

Comments

9

There is one more way to do this apart from the methods given in rest of the answers.

String blockId=jsonarray.getJSONObject(i).getString("block_id");
int block_id = blockId==null ? 0 :  Integer.parseInt(blockId);

Comments

8

You can check for NumberFormatException. Integer.parseInt() will throw NumberFormatException for cases:

  • String is null
  • String is empty ("")
  • String cannot be converted to int for any other reason (say String is "aff" or "1.25")

Basically, it will handle all possible non-integer cases.

Code Example:

private static int convertStringToInt(String str){
    int x = 0;
    try{
        x = Integer.parseInt(str);
    }catch(NumberFormatException ex){
        //TODO: LOG or HANDLE
    }
    return x;
}

Comments

7

You can use following method,

String id = jsonarray.getJSONObject(i).getString("block_id")
int blockId = getBlockId(id);

@NonNull
private Integer getBlockId(String id) {
    Integer blockId= 0;
    try {
        blockId= Integer.parseInt(id);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return blockId;
}

Comments

6
String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;

Comments

6

Try this

 int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;

Comments

3

you can use Integer.getInteger("30").intValue()

Comments

2
int block_id_0 = jObj.optInt("block_id"); 

The ternary condition and multiple code can simply be replaced with optInt function in a single line, which simply

1.) return the default value or 0 if no value is there (depends upon the variant you are using).

2.) Try to convert the value, if the value is available as string

3.) Simply No null or NumberFormat exceptions at all in case of missing key or value

Android docs

int optInt (String name)

int optInt (String name, int fallback)

Maven-Central

int optInt(String key, int defaultValue)

To get a specified default value if no value available

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

jObj.optInt("block_id",defaultvalue);

or

To get a default value as 0 if no value available

Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

jObj.optInt("block_id");

e.g

int block_id = jObj.optInt("block_id",5); 

block_id will be 5 if no key/value available

int block_id_0 = jObj.optInt("block_id"); 

block_id_0 will be 0 if no key/value available

There are other variant of this function available for other datatypes as well , try the docs link above.

Comments

1
String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
    if(str != null)
      number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
    number = 0;
}

Comments

1

Notice.. you could also write it like that

 public static Integer convertToInt(String str) {
    int n=0;
    if(str != null && str.length()>0) {
        n = Integer.parseInt(str);
    }
    return n;
}

but the try/catch method is way more effective and simple and will not cause a system exit if a letter get inside the String (just worth mentioning)

also, it is important to notice that writing the same equation like that:

if(str != null & str.length()>0) {}

or like that:

if(str.length()>0 && str != null) {}

can cause the operation to fail because it will try to count the String even if it is null

Hope I responded to all your questions

Comments

-1

Your function should work fine only when the param is an empty string instead of null If the param is empty string ,Integer.parseInt would throw a NumberFormatException instead of return 0

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.