I have a function which saves Android data in sqlite
but I have to convert the String
data to an Integer
.
Whenever the S
String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;
you can use Integer.getInteger("30").intValue()
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.
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;
}
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;
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);