How do I search for users based on their usernames? I have looked at numerous SO posts on this matter but am still unable to achieve what I want to do.. I have tried to appl
You almost done right but you should add addListenerForSingleValueEvent
after the database reference that already apply orderBy()
, startAt()
, endAt()
like this.
usersRef.orderByChild("username")
.startAt(queryText)
.endAt(queryText+"\uf8ff")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
searchList = new ArrayList<>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
Log.d("USER: ", "" + user.getUsername());
searchList.add(user);
}
adapter = new UserCardAdapter(getContext(), searchList);
recyclerView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("onQueryTextChange: " ,databaseError.getMessage());
}
});
Your use of orderBy()
, startAt()
, and endAt()
is correct according to the documentation.
But the addListener
method must be applied directly to the object returned by the chain of orderByChild()
, startAt()
, and endAt()
methods, and not in a new statement on the DatabaseReference
retrieved with ... .getReference("users")
.
If you use a ChildEventListener:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
usersRef.orderByChild("username")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
.addChildEventListener(new ChildEventListener() {
List<User> searchList = new ArrayList<>();
@Override public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
Log.d("USER: ", "" + user.getUsername());
searchList.add(user);
}
@Override public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
@Override public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
@Override public void onCancelled(DatabaseError databaseError) {}
});