Tiru
Tiru

Reputation: 67

Firebase get all key

HI everyone I want to catch all the keys on my firebase database:

    Users-
         26dfg678-
                 Name: jack
                 Job: Farmer

         43jkhjh4-
                 Name: bill
                 Job: ICT

I want to catch the id: 26dfg678 and 43jkhjh4 and put them in an array. This is my code:

    final DatabaseReference database_nomi = firebaseDatabase.getReference().child("Users");
            database_nomi.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //here                    
                **name[0] = dataSnapshot.getKey();
                    Provee.setText(name[0]);**

                }
                @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) {

                }
            });

if i do this it takes only the last but i want all..

Upvotes: 3

Views: 5116

Answers (1)

guichristovao
guichristovao

Reputation: 450

To do this you need to read through your Firebase snapshot using a ValueEventListener (and addListenerForSingleValueEvent).

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            int i = 0;
            for(DataSnapshot d : dataSnapshot.getChildren()) {
                name[i] = d.getKey();
                i++;
            }
        }
    }//onDataChange

    @Override
    public void onCancelled(DatabaseError error) {

    }//onCancelled
});

This code uses a foreach to read all dataSnapshot children, saving its key in an array at each iteration.

Upvotes: 5

Related Questions