0

image description

Here is my Model. I want to display all users except "peter". Here is my code:

  //iterating through all the values in database
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                User user= postSnapshot.getValue(User.class);
                if (user.getUsername()!="peter"){
                users.add(user);}
            }
            //creating adapter
            adapter = new MyAdapter(getApplicationContext(), users);

            //adding adapter to recyclerview
            recyclerView.setAdapter(adapter);

problem: my list still displays the user Peter!!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

5 Answers5

2

Please use equals method to compare 2 strings:

Replace: if (user.getUsername() != "peter")

With: if (!"peter".equals(user.getUsername()))

Method equals( ) compares the characters inside a String object. Operator == compares two object references.

Alex Kamenkov
  • 891
  • 1
  • 6
  • 16
0

To compare two strings use equals and not ==. Like this

          for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                User user= postSnapshot.getValue(User.class);
                if (!user.getUsername().equals("peter")){
                users.add(user);}
            }
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37
0

== or != checks reference equality, not content equality. Use equals or equalsIgnoreCase please use the search before posting How do I compare strings in Java?

Nick
  • 585
  • 4
  • 11
0
for (DataSnapshot postSnapshot : ref.getChildren()) {
        User user = postSnapshot.getValue(User.class);
        if (!user.getUsername().equals("peter)) { 
            list.add(user); 
    }
Zafar Kurbonov
  • 2,077
  • 4
  • 19
  • 42
0

I thing there is an extra space there in word peter like this " peter" or "peter " try to trim the string and also suggest you to use equalsIgnoreCase insted of equals

 if (!"peter".equalsIgnoreCase(user.getUsername().trim()))

tip- Never compare string using == oprater always use equal() or equalsIgnoreCase() for compare string in java Check Out This

Hope this help you

Sushant Gosavi
  • 3,647
  • 3
  • 35
  • 55