Problem to check list

Asked

Viewed 46 times

2

I have a problem that I don’t understand because here’s the thing: When I go to add an item to the list, it has to check if that item is already in the list but it is not doing that.

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: 1 .gg. | . Gg.
D/D: 3
D/D: 4

The check is receiving that item.name=Gg and named=Gg but it is not passing to if, it is jumping to log 3.

If anyone knows how to solve or do another trick I’d appreciate it:)

2 answers

6


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

if (item.name == nameD)

To:

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

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

if (item.name.equals(nameD))

2

Browser other questions tagged

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