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?

xenteros
  • 15,586
  • 12
  • 56
  • 91
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 4
    Please post a [mcve]. I suspect your String isn't `null` but empty. – Tunaki Sep 27 '16 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`) – Jon Skeet Sep 27 '16 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. – CloudPotato Sep 27 '16 at 14:08
  • JSONObject jObj = jsonarray.getJSONObject(i); int block_id = TextUtils.isEmpty(jObj.getString("block_id"))?0:jObj.getInt("block_id") ; Try this – Zala Janaksinh Oct 12 '16 at 09:38

12 Answers12

24

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;
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
15

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();
}
Community
  • 1
  • 1
xenteros
  • 15,586
  • 12
  • 56
  • 91
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);
Shweta Gulati
  • 566
  • 1
  • 7
  • 17
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;
}
Amber Beriwal
  • 1,568
  • 16
  • 30
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;
}
SachinS
  • 2,223
  • 1
  • 15
  • 25
6
String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;
Ozzz
  • 342
  • 5
  • 12
6

Try this

 int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;
subrahmanyam boyapati
  • 2,836
  • 1
  • 18
  • 28
3

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

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.

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
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;
}
waqas ali
  • 1,238
  • 1
  • 11
  • 17
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

JeanMGirard
  • 171
  • 2
  • 7
-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

azro
  • 53,056
  • 7
  • 34
  • 70
LeoYoung
  • 26
  • 2