0

hier is my firebase Model

"messages" : {
"Johnny_peter" : {
   "-KsjbzGUO90vejwHpzqx" : {
      "message" : "how are u doing",
      "user" : "peter",
      "userName" : "peter"
}
},
"guy_johnz" : {
 "-Ksj5vkO5H4qeleFqojh" : {
     "message" : "merci",
     "user" : "guy",
     "userName" : "steve"
}
"guy_steve" : {
 "-Ksj5vkO5H4qeleFqojh" : {
     "message" : "merci",
     "user" : "williams",
     "userName" : "steve"
}

"steve" is duplicate, I want to retrieve only one time the value of username. I'm using following code

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child("messages");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            for(DataSnapshot dSnapshot : ds.getChildren()) {
                String userName = dSnapshot.child("userName").getValue(String.class);
                Log.d("TAG", userName);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);

how retrieve all value of userName and when the value is duplicate , just take only one value. I want this output: peter, steve

fillobotto
  • 3,698
  • 5
  • 34
  • 58
  • 1
    There is no built-in mechanism to retrieve only one node that has a specific value. The most common way to solve this is to store the messages under the `userName` property. So `/messages/steve/-Ksj5vkO5H4qeleFqojh`, etc. This automatically ensure there is only one node to look in when you want the messages for steve. – Frank van Puffelen Sep 09 '17 at 14:29
  • @Frank van Puffelen, I've updated my post, I dont want to retrieve a specific value but all userName value. I want this output: peter steve –  Sep 09 '17 at 14:45
  • You can't the query is doing what it has to do, you have to make sure the values are unique when created or make them unique for the user searching – cutiko Sep 09 '17 at 14:58

1 Answers1

0

You cannot prevent Firebase from retrieving the duplicate user name without creating a dedicated data structure for that.

But you can drop the duplicate names in your Java code:

public void onDataChange(DataSnapshot dataSnapshot) {
    Set<String> names = new HashSet<String>();
    for(DataSnapshot ds : dataSnapshot.getChildren()) {
        for(DataSnapshot dSnapshot : ds.getChildren()) {
            String userName = dSnapshot.child("userName").getValue(String.class);
            if (!names.contains(userName)) {
                Log.d("TAG", userName);
                names.add(userName);
            }
        }
    }
}

But this isn't a very efficient way to retrieve a list of unique user names. If you want just that, you should consider modeling a data structure for precisely that use-case. See:

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