Saurabh
Saurabh

Reputation: 1005

Parsing an integer value in Android

I am trying to get integer value entered in EditText by user.

EditText eTextValue=(EditText) findViewById(R.id.eId); 
String eTextString=eTextValue.getText().toString();
int eTextValue1=Integer.parseInt(eTextString);

But unluckily I am getting,

unable to parse 9827328 as integer.

I have tried using Integer.valueOf instead of Integer.parseInt but again I am getting the same exception.

I have even used Long datatype to store value instead of int type datatype but nothing seems to be working.Any help over this will be highly appreciated. I have gone through all these links unable to parse ' ' as integer in android , Parsing value from EditText...but nothing seems to be working all of them are landing me in exception.

Upvotes: 0

Views: 559

Answers (4)

yuva ツ
yuva ツ

Reputation: 3703

int id;
id=Integer.parseInt(ed.getText().toString());

Upvotes: 0

Dan Bray
Dan Bray

Reputation: 7832

You need to check whether the string you are parsing is an integer. Try this code:

if (IsInteger(eTextString)
   int eTextValue1=Integer.parseInt(eTextString);

and add this function:

public static boolean IsInteger(String s)
{
   if (s == null || s.length() == 0) return false;
   for(int i = 0; i < s.length(); i++)
   {
      if (Character.digit(s.charAt(i), 10) < 0)
         return false;
   }
   return true;
}

I hope this helps

Upvotes: 0

Gridtestmail
Gridtestmail

Reputation: 1479

Try by entering the following in the XML File under the corresponding EditText element.

android:inputType="number"

Hope this should get you pass the exception.

Upvotes: 0

Barak
Barak

Reputation: 16393

You are using eTextValue as a variable name for two different things (an int and an EditText). You cant do that and expect it to work properly. Change one or the other and it should work better.

Upvotes: 4

Related Questions