'Converting from Editable to int in android
I want to convert the type Editable
from an android EditText
to the type integer to do maths operations on a user input number
I tried the following:
int x=(int)R2.getText().toString();
but it gives me an error of cannot convert a string to int.
Solution 1:[1]
Fine, I got the answer:
int x = Integer.parseInt(R2.getText().toString());
Solution 2:[2]
Use parseInt(), like this -
intX = Integer.parseInt(myEditWidget.getText().toString());
The getText()
method (which is inherited by your EditText widget from the View()
class) returns an object of type Editable
which must be converted to a String type before parseInt() can handle it.
Note that even if your EditText widget is defined with the android:inputType="number"
you will want to catch the exception (NumberFormatException
) that parseInt throws to make sure the value fits in an int!
Solution 3:[3]
Try Integer.ParseInteger(R2.getText())
Solution 4:[4]
I used
int x = Integer.getInteger(R2.getText().toString());
parseInteger
wouldn't work for me.
Solution 5:[5]
My program works this way:
int age = 0;
final EditText txt_age = (EditText) findViewById (R.id.editTextAge);
String str_age = txt_age.getText().toString();
age = Integer.valueOf(str_age);
Solution 6:[6]
In Koltin you can just add toString().toInt(). For example,
var someInt = some_edit_text.toString().toInt()
Solution 7:[7]
In Kotlin: Here we get a text from the edt that is an edit text.
val edt = findViewById<EditText>(R.id.editText)
val id = edt.text
To convert id to int:
id.toString().toInt()
Done!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris Mantle |
Solution 2 | |
Solution 3 | iarwain01 |
Solution 4 | |
Solution 5 | Hulk1991 |
Solution 6 | matua |
Solution 7 | hassan bazai |