Error when comparing an Edittext to a String

Asked

Viewed 303 times

1

I am trying to compare the text inserted in an Edittext with an item in my Arraylist, but the condition is never true.

int aux=-1;

for (int i = 0; i < lista2.size(); i++) {
    if (edContato.getText().equals(lista2.get(i))){
        aux = i;
        break;
    }
}

if (rbExcluir.isChecked()) {
    if(aux>=0){
        principal();
        lista2.remove(aux);
        aplicarLista();
    }
    else {
        dialogo.setTitle("Erro!");
        dialogo.setMessage("Contato não encontrado!");
        dialogo.setNeutralButton("OK", null);
        dialogo.show();
        excluir_alterar();
    }

I’m a beginner in programming for Android and as far as I know, in Java this comparison would work. Am I missing something? This requires some other method of comparison?

1 answer

3

You are comparing one Editable with a String.

The object returned by the method Edittext#gettext() is of the Editable type.

To get the string in Edittext you have to use the method toString() editable’s.

Instead of

edContato.getText().equals(lista2.get(i))

use

edContato.getText().toString().equals(lista2.get(i))
  • I tried that and it didn’t work. It keeps not getting into the condition.

  • So it is because Lista2 has no item equal to the content of Edittext.

  • I put in the middle of the code a Alertdialog that returns me the two values, only for test purposes, and the two contents are apparently identical. I even tried to convert both Edittext and the list item to string and still the condition remains false.

  • What kind is the Arraylist?

  • I didn’t define a type when declaring Arraylist. I am doing the following: I have a Listview (list) to show the data entered in Arraylist (Lista2) with the aid of an Arrayadapter (adp) of type String. Would that be your question?

  • What kind of object are you saving in Arraylist? Strings?

  • I take the contents of an Edittext and add it in Arraylist: Lista2.add(editText1.gettext());

  • I found the bug! I converted the contents of Edittext to String before I added them to the list and now I’m able to remove the items. Thanks for the help!

  • Whenever declaring an Arraylist indicates the type he will receive: ArrayList<String> lista2;. If you had done so the compiler would have warned that there was an error when you used lista2.add(editText1.getText());

Show 4 more comments

Browser other questions tagged

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