java.lang.NumberFormatException using jsonObject.optString ()


Good, I have the following problem only on certain occasions. The app brings information from an external url by means of a Volley request taking the data from a php file with json data. Of 900 devices I had a problem in 17, it is little but there is an error. Mostly the errors come from Galaxy devices.

The lock I see from playConsole:

  at java.lang.Integer.parseInt (
  at java.lang.Integer.parseInt (
  **at com.miapp.yamil.miapp.jugar.onResponse (
  at com.miapp.yamil.miapp.jugar.onResponse (**
  at (
  at$ (
  at android.os.Handler.handleCallback (
  at android.os.Handler.dispatchMessage (
  at android.os.Looper.loop (
  at (
  at java.lang.reflect.Method.invoke (Native Method)
  at$ (
  at (

In these lines I have a conversion from String to Int


number comes from the volley query and is filled in


I can not detect what the problem is because it happens only every so often.

Not: I add, users told me that when this happens the app stops and closes alone.

asked by Yamil Lazzari 27.07.2018 в 15:08

1 answer


The problem is that the value you try to convert sometimes is not a numerical value, since the json sometimes does not have that value.

Remember the use of optString (String name) , if the value you are trying to obtain does not exist, this method returns an empty string ( "" ), this value is obviously not numeric.

You can use this other version of the optString ()

public String optString (String yam,                 String fallback)

and use it in this way defining a default value in case of not finding value, for example "0", this value would be converted without problem to whole:

relleneo.setNumero(jsonObject.optString("CodPreg", "0"));

Another option is to validate if the value is numeric, if it is not numeric to define a default value that is numeric, using the following method:

public static int esNumerico(String number){
    int result = 0; //valor default.
        if(number != null){
            result = Integer.parseInt(number);
    }catch(NumberFormatException nfe){
    return result;

you would use the method in this way:

answered by 27.07.2018 в 16:18