lazydevpro
lazydevpro

Reputation: 127

How to read multiple random key data from firebase android

I am trying to read data from firebase in my android app. This is how it looks. firebase database structure

I want to read the marked data. I am able to read the key of categories child. But unable to read the ids values.

Here's my code:

dbCategories = FirebaseDatabase.getInstance().getReference("categories");

dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()){
            for (DataSnapshot ds: dataSnapshot.getChildren()){
                String name = ds.getKey();
                String ids = ds.child("ids").getValue(String.class);

                Log.i(name, "onDataChange: "+ids);
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Upvotes: 1

Views: 217

Answers (1)

Adel Lahlouh
Adel Lahlouh

Reputation: 1091

You could not connect to the root you want. For example, tcat2, you can modify the ids.

You must specify the path from which you want to read.

You can try this :

dbCategories = FirebaseDatabase.getInstance().getReference("categories");

        dbCategories.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){

                    for (DataSnapshot ds: dataSnapshot.getChildren()){
                       
                      String name = ds.getKey();
                       
                       for(DataSnapshot ds1 : ds.child(name).child("ids").getChildren()){   

                       String ids = ds1.getValue(String.class);

                        Log.i(name, "onDataChange: "+ids);

                       }

                       
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

I hope I helped you.

Upvotes: 3

Related Questions