Search code examples
androidandroid-emulatornumberformatexception

NumberFormatException in device but not in emulator


I run my app in the emulator and everything works fine, but when I run it in my device ( Huawei u8650) I get NumberFormatException:

GraphViewData[] aux2 = new GraphViewData[aux.length];
     for(int i=0;i<aux.length;i++)
     {
         System.out.println("reps "+Repetitions+", dato "+i+" = "+aux[i]);
         if(aux[i] != null)
         {
             try{
         aux2[i]= new GraphViewData(i, Double.parseDouble(aux[i]));
             }catch(Exception w)
         {
                 Toast.makeText(this, "num: "+aux[i], Toast.LENGTH_LONG).show();
                 Toast.makeText(this, w.getMessage(), Toast.LENGTH_LONG).show();
         }
         }
}

The exception is at : aux2[i]= new GraphViewData(i, Double.parseDouble(aux[i])); OK, you would think that aux[i] would have an incorrect format to parse to double but all are number like this: 70.5 or like this 84 So I don´t know why it gives that exception only in real device but not in emulator.

Any suggestions? thanks in advance.


Solution

  • OK, the answer is using this code:

    public double stringToDouble(String s) {
    
           NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
        nf.setGroupingUsed(false);
        ParsePosition parsePosition = new ParsePosition(0);
        Number n = nf.parse(s, parsePosition);
        if (n == null || parsePosition.getErrorIndex() >= 0 || parsePosition.getIndex() < s.length())
        {
          /* not a valid number */
        }
        return n.doubleValue();
    }
    

    This works for me