3

I am retrieving all the users from firebase database and displaying them in a recyclerView. It displays the town,username and image. I am able to retrieve but it only displays one user instead of all the users.The database has many users but only one is being displayed.Any suggestions will really help.

Here is the bit that retrieves the users

    public void showUsersList() {

    mdatabaseRef = FirebaseDatabase.getInstance ().getReference ( "Users" );

        mdatabaseRef.addValueEventListener ( new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                mcontacts.clear ();

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren ()) {

                   Contacts contactsz = dataSnapshot1.getValue (Contacts.class);
                    mcontacts.add ( contactsz );

                }

                mAdapter = new UsersAdapter ( getApplicationContext () , mcontacts );
                recyclerView.setAdapter ( mAdapter );

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

                Toast.makeText ( FindFriendsActivity.this , " " , Toast.LENGTH_SHORT ).show ();

            }
        } 



    }

This the Adapter class

     private Context mcontext;
    private List<Contacts> mcontacts;

    public UsersAdapter(Context context, List<Contacts> contacts){

        mcontext = context;
        mcontacts = contacts;

    }


    @NonNull
    @Override
    public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup , int i) {

        View v = LayoutInflater.from ( mcontext ).inflate ( R.layout.users_display_layout, viewGroup, false );
        return new UsersViewHolder ( v );

    }

    @Override
    public void onBindViewHolder(@NonNull UsersViewHolder usersViewHolder , int i) {

        Contacts contactsCurrent  = mcontacts.get ( i );
        usersViewHolder.nameOfUser.setText ( contactsCurrent.getName () );
        usersViewHolder.nameOfTown.setText ( contactsCurrent.getTownname () );

        Picasso.get ().load ( contactsCurrent.getImage () ).into ( usersViewHolder.usersImage );

    }

    @Override
    public int getItemCount() {
        return  mcontacts.size ();
    }

    public class UsersViewHolder extends RecyclerView.ViewHolder{

             public TextView nameOfUser;
             public TextView nameOfTown;
             public CircleImageView usersImage;

        public UsersViewHolder(@NonNull View itemView) {
            super ( itemView );

            nameOfUser = itemView.findViewById ( R.id.user_profile_name );
            nameOfTown = itemView.findViewById ( R.id.user_town_name );
            usersImage = itemView.findViewById ( R.id.users_profile_image );


        }
    }

}
`````````````````````````````````````````````````````````````````

Here is the Contacts class

public class Contacts {

    public String Name,townname,image;


    public Contacts(){

    }


    public Contacts(String name , String townname , String image) {
        Name = name;
        this.townname = townname;
        this.image = image;

    }


    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getTownname() {
        return townname;
    }

    public void setTownname(String townname) {
        this.townname = townname;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}


  [1]: https://i.stack.imgur.com/dFD6z.jpg
Benjamin Hue
  • 218
  • 2
  • 9

5 Answers5

3

I dont think Firebase lets you fetch all User Account info, Here is what i did when working in a project, where I used readtime DataBase to save user information when they signed up in this format(can update info later using Uid), then fetch this database field for recyclerView.

Note : User Authentication UID should be used for fetching data.

enter image description here

also try this method for recyclerView and not onDataChange for this scenario.

mFirebaseDatabaseRef.child("Users").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                String retrievename = String.valueOf((String) dataSnapshot.child("Name").getValue());
                String retrievecity = String.valueOf((String) dataSnapshot.child("townname").getValue());
                String retrieveProfileImage = String.valueOf((String) dataSnapshot.child("image").getValue());

                if (!retrievename.equals("null")) {

                    usersnames.setText ( retrievename );
                    userstown.setText ( retrievecity );
                   Picasso.get().load ( retrieveProfileImage ).into ( circleImageView );
                }
                mAdapter.notifyDataSetChanged();
            }
            @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) { }
        });
    }
Rajiv Reddy
  • 339
  • 1
  • 11
  • I am fetching only the name,image and city, for the profile info. – Benjamin Hue Apr 08 '19 at 08:04
  • yes you may create the database fields as per your requirements, all the above details contain my project required fields. – Rajiv Reddy Apr 08 '19 at 09:03
  • I have updated and used your updated code but its still displaying one user – Benjamin Hue Apr 08 '19 at 09:54
  • then you will have to set logs and Debug to identify the issue. Only if i look at the code i may understand the issue. As i am currently using the above code and it works perfectly fine. – Rajiv Reddy Apr 08 '19 at 09:58
  • For me i think i have a problem in initializing the adapter and adding the items to the recyclerview while notifying the adapter. Thats the part that keeping me stuck. – Benjamin Hue Apr 08 '19 at 10:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191437/discussion-between-benjamin-hue-and-lazy-teddy). – Benjamin Hue Apr 08 '19 at 10:08
2

For me, I will store all the child item into a list, then pass the list to recyclerView adapter inside onDataChange method.

Edit

From you latest code, you are not adding return object into mcontacts list. Check below code.

 for (DataSnapshot npsnapshot : dataSnapshot.getChildren()){
        Contacts contacts =npsnapshot.getValue(Contacts.class);
        mcontacts.add(contacts);  // you miss this line
     }
        mAdapter = new UsersAdapter ( getApplicationContext () , mcontacts );
        recyclerView.setAdapter ( mAdapter );
John Joe
  • 12,412
  • 16
  • 70
  • 135
1

My suggation is create class of user

class User
{
  //filds like name,image etc
}

Now you recyclerView adapter class

class RcUsersAdapter extends RecyclerView.Adapter<RcUsersAdapter.ViewHolder>
{
   public ArrayList<User> userList;
   public RcUsersAdapter(Context context,ArrayList<Users> userList)
   {
    this.context = context;
    this.userList = userList;
   }

   //... other methods

}

Know in your Activity or Fragment class initialize the adapter with

RcUsersAdapter rcUsersAdapter  = new RcUsersAdapter(context,new ArrayList<User>());

Know when you get the data

rcUsersAdapter.userList.add(UserClassObject);
rcUsersAdapter.notifyItemInserted(rcUsersAdapter.getItemCount());
Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65
0

How about use FirebaseRecyclerAdapter(FirebaseRecyclerOptions).

Akio Alex
  • 316
  • 1
  • 9
  • 1
    what make you feel that `FirebaseRecyclerAdapter` will solved OP's issue? – John Joe Apr 08 '19 at 07:37
  • 1
    FirebaseRecyclerAdapter is very powerful adapter realtime get data from FirebaseDatabase. It support change value listener and item click callback and onCreate init. All supported. I am always use this. very good adapter for firebase – Akio Alex Apr 08 '19 at 07:40
  • 1
    Maybe it is powerful, but OP using `recyclerView` right now and the issue is all the item from `firebase` are not getting retrieved. – John Joe Apr 08 '19 at 07:42
  • maybe it helped? I don't know, just guessing :) – John Joe Apr 08 '19 at 07:44
  • Nope, i'm not the one that facing issue right now. Thanks :) – John Joe Apr 08 '19 at 07:52
0

Your code is not complete as comment @HemendraGangwar. And as @JohnJoe wrote you need to add every child in method onDataChange(). I suggest you to make something like this:

public void onDataChange(DataSnapshot dataSnapshot) {
    if (dataSnapshot.exist) {
         for (DataSnapshot ds : dataSnapshot.getChildren ()){
              // Create your object wrapper with fields that you have in db.
              MyUser user = ds.getValue(MyUser.class);
              // Method in adapter that will add the user to list 
              // and run notifyItemInserted(insertedPosition);
              adapter.addUser(user);
         }
    }
}

Set your usersnames.setText() via DP ViewHolder in adapter method onBindViewHolder like: holder.usersnames.setText(user.getName());.

Vadim Eksler
  • 865
  • 9
  • 24