Collect values from EditText

1

I have a little doubt on Android. Suppose I have an EditText, in which the user will enter a number by keyboard. How can I collect that value? Let's see, I'll do it as if it were a text string, which would be where I do this:

private EditText et1;

et1 = (EditText)findviewbyid(R.id.et1);

String texto = et1.getText().toString();

But do not do it if instead of text was a number, for example a number referring to age. How would that value be collected? Thanks and best regards!

    
asked by Sergio AG 09.03.2018 в 01:07
source

4 answers

2

You can use this to convert it to integer or double (see below):

String texto = et1.getText().toString();

For a whole number, any of these 2 forms:

int numero = Integer.parseInt(texto);
int numero = Integer.parseInt(et1.getText().toString());

For decimals:

double decimal = Double.parseDouble(et1.getText().toString());
double decimal = Double.parseDouble(texto);

You can add .trim() to skip spaces in white that could be before or after the number entered:

int numero = Integer.parseInt(et1.getText().toString().trim());
    
answered by 09.03.2018 / 01:32
source
2

Everything you pick up will come as a String, what you should do is make a parse, for example:

Int edad = Integer.parse(et1.getText().toString())
    
answered by 09.03.2018 в 01:13
1

I recommend that you take some safety measures when pairing:

String sEdad = et1.getText().toString();
Int iEdad = 0;
if("" != sEdad)  iEdad = Integer.parse(sEdad);

With this you avoid a conversion error in case the parse method is called and the String is empty

    
answered by 09.03.2018 в 01:31
1

If it's a number it's the same procedure, actually the method getText () returns the text that is displayed by TextView .

Therefore it is indifferent if it is a String or a number.

But if you want to get the value numerico , then you have to convert it, you can use for this Integer.parse() :

Int valor = Integer.parse(et1.getText().toString())

As a best practice, use the trim() method to avoid possible spaces in the content of your EditText :

Int valor = Integer.parse(et1.getText().toString().trim())
    
answered by 09.03.2018 в 01:11