Search code examples
javaandroidfirebasefirebase-realtime-databasefirebaseui

Not getting all results for RecyclerView from firebase


My app has two categories of users shop owner and buyers. When shop owner adds a shop I use his UID and then pushkey to add a shop like this:

this

In the Image "83yV" and "FmNu" are the shop owners and they add 2 and 1 shop respectively.

Now for buyers, I want to show the whole list of shops in a Recycler View.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_shops_avtivity);

    shopsDB = FirebaseDatabase.getInstance().getReference().child("shops");
}

@Override
protected void onStart() {
    super.onStart();
    FirebaseRecyclerAdapter<Shop,ShopViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Shop, ShopViewHolder>(
            Shop.class,
            R.layout.shop_single_layout,
            ShopViewHolder.class,
            shopsDB)
}

The problem is when I point my Firebase Recycler Adapter to shopDB, it returns two empty cardView like this:

this

When I point it to specific child like

shopsDB = FirebaseDatabase.getInstance().getReference().child("shops").child("83yV24a3AmP15XubhPGApvlU7GE2");

It returns shops add by "83yV".

How can I get the shops added by other owners also? Preferably without altering current DB or creating one DB with all shops in it within on child.


Solution

  • To achieve this, you need to use getChildren() method twice, once to get all the users and second to get all the shops.

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference shopsRef = rootRef.child("shops");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                for(DataSnapshot dSnapshot : ds.getChildren()) {
                    String name = dSnapshot.child("name").getValue(String.class);
                    Log.d("TAG", name);
                }
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    shopsRef.addListenerForSingleValueEvent(eventListener);
    

    Using this code, you'll be able to display all shop names to the buyers.