How to pass value from editText to attribute to type int on Android?

2

I have a question regarding the storage of value from EditText to attributes of type int of a class. For attributes of type String I do this:

objEquipamento.setMarcaModelo(edtMarcaModelo.getText().toString());

But when my attribute is of type int ? and I want to get a number? do I have to convert the value or does some method exist for int ?

    
asked by anonymous 31.05.2014 / 23:33

3 answers

1

Use Integer.html#parseInt :

objEquipamento.setMarcaModelo(Integer.ParseInt(edtMarcaModelo.getText().toString().trim()));

If Integer.html#parseInt is unable to perform the conversion, an exception NumberFormatException is released, if you prefer to return a default value instead, do:

public static int MyParseInt(String texto, int valorPadrao) {
   try {
      return Integer.parseInt(texto);
   } 
   catch (NumberFormatException e) {
      return valorPadrao;
   }
}

Use this:

objEquipamento.setMarcaModelo(MyParseInt(edtMarcaModelo.getText().toString().trim(), 0));

For double , use Double.html#parseDouble .

    
01.06.2014 / 00:18
2

You will have to use the Integer.ParseInt () as follows:

try{
    objEquipamento.setMarcaModelo(Integer.ParseInt(edtMarcaModelo.getText().toString()));
} catch (NumberFormatException e) {
      //erro ao converter
}

It is important that you put the treatment and force the user to actually type an Integer as follows in the xml:

<EditText android:numeric="integer" ..../>
    
01.06.2014 / 03:03
1

You can use parseInt instead, but since it is an editText, a non-numeric character can be entered, causing an exception, so this needs to be handled

    
01.06.2014 / 02:49