I have a little question on Android. Suppose I have an EditText, in which the user will enter a number by keyboard. How can I collect this value? Let's see, I know how to do it as if it were a text string, which would then be where I do this:
private EditText et1;
et1 = (EditText)findviewbyid(R.id.et1);
String texto = et1.getText().toString();
But I won't do it if instead of text it was a number, for example a number referring to age. How would this value be collected? Thanks and greetings!
You can use this to convert to integer or double (see below):
For an integer, either of these 2 ways:
For decimals:
You can add
.trim()
to skip whitespace that may be before or after the entered number:Everything you collect will come to you as a String, what you have to do is parse it, for example:
If it is a number it is the same procedure, actually the getText() method returns the text that is displayed by the
TextView
.So it doesn't matter if it's a String or a number.
But if you want to get the value
numerico
then you have to convert it, you can use for thisInteger.parse()
:As a best practice use the method
trim()
to avoid possible spaces in the content of yourEditText
:I recommend that you take some security measures when parsing:
With this you avoid a conversion error in case the parse method is called and the String is empty