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

Asked

Viewed 5,189 times

2

I have a question about the value store coming from EditText for attributes of type int of a class. For attributes of the type String I do so:

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

But when my attribute is like int? and I want to write a number? I have to convert the value or there is some method to int?

3 answers

2

You will have to use the method 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 processing and force the user to actually type an Integer as follows in xml:

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

    very good this tip in xml, thank you

1


Use Integer.html#parseInt:

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

If Integer.html#parseInt cannot perform the conversion, an exception NumberFormatException is launched, 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 like this:

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

To double, use Double.html#parseDouble.

  • @Vinicius There is yes, http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

  • for double type attributes I do so? objServico.setValorTotal(Double.parseDouble(edtMarcaModel.gettext(). toString()));

1

You can use parseint yes, but since it is an editText, you can insert a non-numeric character, causing an exception, so this needs to be handled

Browser other questions tagged

You are not signed in. Login or sign up in order to post.