FirebaseUI with RecycleView

纵饮孤独 提交于 2019-12-01 14:49:43

To solve this, please follow the next steps:

  1. change your model to look like this:

    public class Places {
        private String image, name;
    
        public Places() { }
    
        public Places(String image, String name) {
            this.image = image;
            this.name = name;
        }
    
        public String getImage() { return image; }
        public String getName() { return name; }
    }
    

    The fields from your model class should look exactly like the one from your database. In your code are different. See name_place vs. name.

  2. Make your firebaseRecyclerAdapter varaible global:

    private FirebaseRecyclerAdapter<Places, PlaceViewHolder> firebaseRecyclerAdapter;
    
  3. Remove FirebaseRecyclerAdapter<Places, PlaceViewHolder> from the onCreate() method.

  4. Add the following lines of code in the onStart() and onStop() methods.

    @Override
    protected void onStart() {
        super.onStart();
        firebaseRecyclerAdapter.startListening();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        if(firebaseRecyclerAdapter != null) {
            firebaseRecyclerAdapter.stopListening();
        }
    }
    

This is a complete example on how you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.

Edit:

To simply display those names in the logcat, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            Log.d("TAG", name);
            Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!