I have a function which saves Android data in sqlite
but I have to convert the String
data to an Integer
.
Whenever the S
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();
}