Problem checking list

2

I have a problem that I do not understand because, it is the following: When I add an item to the list, it has to check if this item is already in the list but it is not doing it.

if(textNameD.getText().length() > 0 && textNota.getText().length() > 0) {
        String nameD = textNameD.getText().toString();
        for (int i = 0; i < list.size();i++){
            listItem item = list.get(i);
            Log.d("D","1 ."+nameD+". | ."+item.name+".");
            if (item.name == nameD) {
                Log.d("D","2");
                showNotificacion(view,"A disciplina "+item.name+" já existe!");
                return;
            }
            Log.d("D","3");
        }
        Log.d("D","4");
        add(textNameD.getText().toString(),stringToInt(textNota.getText().toString()));
        textNameD.setText("");
        textNota.setText("");
    }else {
        showNotificacion(view,"Preenche todos os espacos!");
    }

And you're getting the following in the log:

  

D / D: 1g. | .gg.   D / D: 3
  D / D: 4

The check is to receive that item.name = gg and the nameD = gg but it is not passing to if, it is jumping to log 3.

If anyone knows how to solve or make another way, thanks:)

    
asked by anonymous 08.12.2016 / 17:19

2 answers

6

== compares references. Two Strings can have different references, even with equal values. Try changing:

if (item.name == nameD)

To:

if (Objects.equals(item.name, nameD))

Note. In the above example, I used Object#equals because one of the compared objects could be null. If you are sure that one of the objects is not null, you can use String#equals direct:

if (item.name.equals(nameD))
    
08.12.2016 / 17:33
2

Try this:

  if (item.name.equals(nameD)) {
                Log.d("D","2");
                showNotificacion(view,"A disciplina "+item.name+" já existe!");
                return;
            }

Here's a read on this error

    
08.12.2016 / 17:31