How do I convert a string into an integer?
I have a textbox I have the user enter a number into:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
And the value is assigned to the string hello
.
I want to convert it to a integer so I can get the number they typed; it will be used later on in code.
Is there a way to get the EditText
to a integer? That would skip the middle man. If not, string to integer will be just fine.
Use regular expression:
output:
See the Integer class and the static
parseInt()
method:http://developer.android.com/reference/java/lang/Integer.html
You will need to catch
NumberFormatException
though in case of problems whilst parsing, so:You can also do it one line:
Reading from order of execution
findViewById(R.id.button1)
((Button)______)
to cast theView
as aButton
.GetText()
to get the text entry from Button.toString()
to convert the Character Varying to a String.ReplaceAll()
with"[\\D]"
to replace all Non Digit Characters with "" (nothing)Integer.parseInt()
grab and return an integer out of the Digit-only string.Best way to convert your string into int is :
Try this code it's really working.
You can use the following to parse a string to an integer:
int value=Integer.parseInt(textView.getText().toString());
(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.
(2) input: "abdul" then it will throw an exception that is NumberFormatException. So to solve this we need to use try catch as I have mention below:
You may also want to refer to the following link for more information: http://developer.android.com/reference/java/lang/Integer.html