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?
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.
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.
null is not a valid representation of integer number. Integer. parseInt() requires that the string be parsed is a vaild representation of integer number.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With