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

前端 未结 2 1686
伪装坚强ぢ
伪装坚强ぢ 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:31

    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());
                    }
                });
    
    0 讨论(0)
  • 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<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) {}
        });
    
    0 讨论(0)
提交回复
热议问题