Asset Bekbossynov
Asset Bekbossynov

Reputation: 357

How to get reference of child firebase database

I am trying to get reference of smth3 from my firebase database

|smth1
---|smth2
   ---|smth3
      ---|smth4
      ---|smth5

Code:

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("smth1")
        .child("smth2");
 mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int count = 0;
                DataSnapshot needSnapshot = null;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){                       
                        needSnapshot = snapshot;
                        if(count == getPosition()){
                            break;
                        }
                        count++;

                }


                mDatabase.child(needSnapshot.getKey()).removeValue();
                notifyItemRemoved(getPosition());
                notifyItemRangeChanged(getPosition(), getItemCount());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

this code always removes smth2.

after getting reference i want to remove it with all its children and values Please help to get ref of smth3

Upvotes: 0

Views: 11256

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

The Firebase Database only stores values and their associated path. If there are no values under a given path, that path is automatically removed. Since smth3 is the only value under smth2, removing smth3 will also remove smth2.

This logic goes hand in hand with the fact that smth2 is automatically created when you write a value under smth3. Paths are automatically created as needed and removed when they are empty.

Upvotes: 3

Jorge Barrios
Jorge Barrios

Reputation: 507

First you need add the Realtime Database to your app by adding this dependency to your app-level build.gradle file:

compile 'com.google.firebase:firebase-database:11.0.2'

Then you can read/write anything to your database like this:

private DatabaseReference mDatabase;

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

mDatabase.child("smth1").child("smth2").child("smth3").removeValue();

It is well documented here.

Upvotes: 0

Related Questions