73

Basically, I want an EditText in Android where I can have an integer value entered into. Perhaps there is a more appropriate object than EditText for this?

4 Answers 4

154

For now, use an EditText. Use android:inputType="number" to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())).

In the future, you might consider a NumberPicker widget, once that becomes available (slated to be in Honeycomb).

4
  • Offhand, in Java, do you know what is the integer equivalent of the "number" inputType android attribute? (ie: EditText.setInputType(integer)). Thanks.
    – Rob S.
    Feb 4, 2011 at 22:27
  • @Rob S.: InputType.TYPE_CLASS_NUMBER, as indicated in the documentation. Feb 4, 2011 at 23:31
  • 7
    I think this should be expanded to account for cases when the editText has no value (i.e. editText.getText() == ""). Jun 20, 2013 at 17:32
  • 4
    Exception is raised when the edittext is null.When giving like Integer.parseInt(myEditText.getText().toString())
    – Sharath
    Nov 18, 2015 at 18:12
12

Set the digits attribute to true, which will cause it to only allow number inputs.

Then do Integer.valueOf(editText.getText()) to get an int value out.

2
  • 5
    won't this cause The method valueOf(String) in the type Integer is not applicable for the arguments (Editable) error? Sep 26, 2013 at 5:26
  • 2
    @zhangxaochen - getText() is not String. It is needed to call getText().toString() Jan 9, 2016 at 22:07
9

First of all get a string from an EDITTEXT and then convert this string into integer like

      String no=myTxt.getText().toString();       //this will get a string                               
      int no2=Integer.parseInt(no);              //this will get a no from the string
1

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

3
  • As other answers have pointed out, though, it's really more of an "and" than an "or", right? If you do 1, then you still need to do 2, the XML can't alter what you get as a return type in Java, and if you do 2, then you'll want to do 1 to ensure safe input. You'll always need to do 2 and it's best to just do both.
    – Tim M.
    Aug 23, 2019 at 13:03
  • Thanks Tim, it was a typo!
    – Girish B.R
    Oct 14, 2019 at 9:15
  • (to put those comments in context, the issue has since been fixed via edit)
    – Tim M.
    Dec 18, 2019 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.