evan
evan

Reputation: 431

How to get children of root node in Firebase for Android

I have the following tree structure

[1]

I need to get the information Name and Details alone and their children.

I have done this, but doesn't run and shuts down the application when executed:

info = FirebaseDatabase.getInstance().getReference();
        info.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot infoSnapshot: dataSnapshot.getChildren()) {
                    Log.i(TAG, infoSnapshot.child(info.toString()).getValue(String.class));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.i(TAG, "onCancelled", databaseError.toException());
            }
        });

How to solve this?

Upvotes: 0

Views: 3247

Answers (3)

Alex Mamo
Alex Mamo

Reputation: 138824

To get the data from the root node, please use the code below:

info = FirebaseDatabase.getInstance().getReference();
info.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String child = ds.getKey();
            Log.d("TAG", child);
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.i(TAG, "onCancelled", databaseError.toException());
    }
});

The output will be:

details
name

Upvotes: 6

Shashvat Shah
Shashvat Shah

Reputation: 11

Once you get the data snapshot, then you can easily iterate through all the data received..

info = FirebaseDatabase.getInstance().getReference();
    info.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot infoSnapshot:dataSnapshot.child("details").getChildren()) {
                Log.i(TAG, infoSnapshot.getValue(String.class));
            }
            for(DataSnapshot infoSnapshot:dataSnapshot.child("name").getChildren()){
                Log.i(TAG, infoSnapshot.getValue(String.class));
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i(TAG, "onCancelled", databaseError.toException());
        }
    });

Upvotes: 1

Oussema Aroua
Oussema Aroua

Reputation: 5329

Delete this line is useless :

mDatabase= FirebaseDatabase.getInstance().getReference();

and change this like

info = FirebaseDatabase.getInstance().getReference(mDatabase.toString());

to

info = FirebaseDatabase.getInstance().getReference();

also this:

Log.i(TAG, infoSnapshot.child("root").getValue(String.class));// the root node doesn't exists 

Upvotes: 0

Related Questions