Yasir
Yasir

Reputation: 77

I am getting NumberFormatException while converting String into Intger

I have an php api which give me array like this:

11%0%0%801%0%0%812%0%0%640%33%6

Above response is going to be stored in "String a"

try{
    //... Some code of my application which is not relavant to show
    String a = response.toString();
    String tokens = a.split("%");
    for (String str : tokens)
    {
        Log.e("log_tag", str);
    }
    String ds = tokens[0];
    int i_ds = Integer.parseInt(ds);
    Log.e("log_tag", "data is: "+i_ds);
}catch (Exception e) {
     Log.e("log_tag","Error: " + e.toString());
}

I am getting following in my DDMS:

Tag         Text
log_tag     11
log_tag     0
log_tag     0
log_tag     801
log_tag     0
log_tag     0
log_tag     812
log_tag     0
log_tag     0
log_tag     640
log_tag     33
log_tag     6
log_tag     java.lang.NumberFormatException: Invalid int:"11"

Upvotes: 0

Views: 140

Answers (2)

think-Android
think-Android

Reputation: 111

String.split returns a String[]

Replace String tokens = a.split("%"); with String[] tokens = a.split("%");

Upvotes: 0

ug_
ug_

Reputation: 11440

I Just copied and pasted your code, although other comments do state the truth that you do need to make this change: String [] tokens = a.split("%");

Looks like php is passing you some fun hidden characters! Theres a hidden character before the number 11, I would sanitize your string by doing the following

tokens[0].replaceAll("[^0-9]", "");

Upvotes: 3

Related Questions