M Najib Laaziz
M Najib Laaziz

Reputation: 55

How to convert String taken from a TextField view to an int

I have a TextField in a layout and I would like to retrieve it and convert it to an integer to put it in my database. I have used the following code but it keeps giving me some exception

EditText agefield = (EditText) findViewById(R.id.agefield);             
int age = Integer.parseInt(agefield.getText().toString());

Upvotes: 0

Views: 9692

Answers (2)

pelumi
pelumi

Reputation: 1660

Hi to achieve that in android; your exact question has been answered here.

In addition I will advise that you double check to verify that you have called the setContentView(R.layout.main) for the activity concerned i.e ensure that xml file containing the agefield edittext has been set to the contentview before attempting to evoke EditText agefield = (EditText) findViewById(R.id.agefield). If it has not then you will get a null pointer because your edittext field will be null. After confirming that ensure that the value in the edittext is a valid number and its not empty.

I think the setContentView is the problem because i had a similar experience recently.

Feel free to mark as the answer if this answers your question. Hope this helps, good luck!

Upvotes: 0

Satya
Satya

Reputation: 8881

if Java this line

int age = Integer.parseInt(agefield.getText().toString());

can be re-written as

int age = Integer.parseInt(agefield.getText());

Upvotes: 3

Related Questions