java.lang.NumberFormatException using jsonObject.optString ()

2

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:

    java.lang.NumberFormatException: 
  at java.lang.Integer.parseInt (Integer.java:620)
  at java.lang.Integer.parseInt (Integer.java:643)
  **at com.miapp.yamil.miapp.jugar.onResponse (jugar.java:319)
  at com.miapp.yamil.miapp.jugar.onResponse (jugar.java:42)**
  at com.android.volley.toolbox.JsonRequest.deliverResponse (JsonRequest.java:83)
  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run (ExecutorDelivery.java:106)
  at android.os.Handler.handleCallback (Handler.java:789)
  at android.os.Handler.dispatchMessage (Handler.java:98)
  at android.os.Looper.loop (Looper.java:251)
  at android.app.ActivityThread.main (ActivityThread.java:6589)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:240)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

In these lines I have a conversion from String to Int

   *numero.setText(relleneo.getNumero());
    numeros=Integer.parseInt(numero.getText().toString());*

number comes from the volley query and is filled in

*relleneo.setNumero(jsonObject.optString("CodPreg"));*

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
source

1 answer

1

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.
    try{
        if(number != null){
            result = Integer.parseInt(number);
        }
    }catch(NumberFormatException nfe){
        nfe.printStackTrace();
    }
    return result;
}

you would use the method in this way:

  numeros=Integer.parseInt(esNumerico(numero.getText().toString()));
    
answered by 27.07.2018 в 16:18