FirebaseUI with RecycleView

前端 未结 1 1283
一个人的身影
一个人的身影 2021-01-17 06:11

After uptade syntax of FirebaseUI, can\'t work without onPopulateViewHolder method. I read the doc of FirebaseUI and did the same. After running app, Recy

相关标签:
1条回答
  • 2021-01-17 06:46

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