GEOFFREY MWANGI GEOFFREY MWANGI - 2 months ago 6
Java Question

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

Am new to Java and 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

This is my code which fails whenever the value is
null


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


The id above is converted to a integer

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

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?

Answer

Simply use the built-in method JSONObject#getInt(String), it will automatically convert the value as an int by calling 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;
Comments