我正在尝试使用Firebase实时数据库在RecyclerView中从其主键中显示用户,但是每次尝试RecyclerView为空时。我尝试了很多教程,但似乎无济于事 这是我的数据库的外观:
这是我使用RecyclerView的课程
public class UsersActivity extends AppCompatActivity {
private RecyclerView userslist;
private DatabaseReference ref;
private List<Users> mUsers;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_users );
ref = FirebaseDatabase.getInstance ().getReference ("users");
userslist = (RecyclerView) findViewById ( R.id.users_list );
userslist.setLayoutManager ( new LinearLayoutManager ( this ) );
mUsers=new ArrayList<> ( );
readUsers ();
ref.addValueEventListener ( new ValueEventListener () {
@Override
public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren ()){
Users users=dataSnapshot.getValue (Users.class);
mUsers.add ( users );
}
}
@Override
public void onCancelled (@NonNull DatabaseError databaseError) {
}
} );
}
public void readUsers(){
FirebaseUser firebaseUser= FirebaseAuth.getInstance ().getCurrentUser ();
DatabaseReference reference=FirebaseDatabase.getInstance ().getReference ("users");
reference.addValueEventListener ( new ValueEventListener () {
@Override
public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled (@NonNull DatabaseError databaseError) {
}
} );
}
@Override
protected void onStart () {
super.onStart ();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users> ()
.setQuery ( ref, Users.class )
.build ();
FirebaseRecyclerAdapter<Users, FindFriendViewHolder> adapter = new FirebaseRecyclerAdapter<Users, FindFriendViewHolder> ( options ) {
@Override
protected void onBindViewHolder (@NonNull FindFriendViewHolder findFriendViewHolder, int i, @NonNull Users users) {
findFriendViewHolder.userName.setText ( users.getName () );
}
@NonNull
@Override
public FindFriendViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from ( parent.getContext () ).inflate ( R.layout.users_template, parent, false );
FindFriendViewHolder viewHolder = new FindFriendViewHolder ( view );
return viewHolder;
}
};
userslist.setAdapter ( adapter );
adapter.startListening ();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView profileImage;
public FindFriendViewHolder (@NonNull View itemView) {
super ( itemView );
userName = itemView.findViewById ( R.id.username1 );
profileImage = itemView.findViewById ( R.id.profilepicture );
}
}
}
用户名适配器
public class Users {
public String name;
public Users(){}
public Users(String name){
this.name=name;}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
}
我希望RecyclerView的所有用户都位于其主键之后。