Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String to int. Set the int to 0 if String is null

Tags:

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?

like image 800
Geoff Avatar asked Sep 27 '16 14:09

Geoff


People also ask

Can null be assigned to int?

Assigning Null to Variables null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.

Can we convert empty string to int in java?

What if we passed a data type other than an int in parseInt() or valueOf()? The program will throw a NumberFormatException upon passing values other than numerics. An empty or null string is also liable for the same error and would not convert a string to an integer in java.

Is null string or integer?

null is not a valid representation of integer number. Integer. parseInt() requires that the string be parsed is a vaild representation of integer number.


1 Answers

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; 
like image 129
Nicolas Filotto Avatar answered Oct 09 '22 12:10

Nicolas Filotto