Firebase Android - startAt() and endAt() not working correctly?

前端 未结 2 1687
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 14:21

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 14:48

    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 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) {}
        });
    

提交回复
热议问题