sherif
sherif

Reputation: 531

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.

Upvotes: 18

Views: 29929

Answers (7)

hassan bazai
hassan bazai

Reputation: 459

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!

Upvotes: 0

matua
matua

Reputation: 627

In Koltin you can just add toString().toInt(). For example,

var someInt = some_edit_text.toString().toInt()

Upvotes: 0

sherif
sherif

Reputation: 531

Fine, I got the answer:

int x = Integer.parseInt(R2.getText().toString());

Upvotes: 35

Toob
Toob

Reputation: 1

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);

Upvotes: 0

PaulP
PaulP

Reputation: 2325

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!

Upvotes: 10

Simply Brian
Simply Brian

Reputation: 1591

I used

int x = Integer.getInteger(R2.getText().toString()); 

parseInteger wouldn't work for me.

Upvotes: 1

iarwain01
iarwain01

Reputation: 424

Try Integer.ParseInteger(R2.getText())

Upvotes: 5

Related Questions