How can I get the Key of a child in Firebase?

I have this structure on my Database

enter image description here

What I would like to do is to be able to delete any child within MBlog so far I don't have a clear view on how to get these child keys to be able to use the .removeValue at the moment what I have is:

private void deletePost() {
    String uploadId = mPostDatabase.getKey();
    DatabaseReference pRef = FirebaseDatabase.getInstance().getReference("https://farmr2-1.firebaseio.com/Mblog").child(uploadId);
    pRef.removeValue();

    Toast.makeText(this, "field deleted", Toast.LENGTH_LONG).show();

    startActivity(new Intent(CowDet.this, PostListActivity.class));
    finish();
}

Upvotes: 0

Views: 451

Answers (2)

Darcia14
Darcia14

Reputation: 224

Create a DatabaseReference and iterate it like this.

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
        db.child("Mblog").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (task.isSuccessful())
                {
                        Iterable<DataSnapshot> iterable = task.getResult().getChildren();
                        Iterator<DataSnapshot> iterator = iterable.iterator();
                        while (iterator.hasNext()) {
                            DataSnapshot child = iterator.next();
                            System.out.println(child.getKey()); // use this key
                        }
                }
            }
        });

Upvotes: 1

Dharmaraj
Dharmaraj

Reputation: 50840

I am not sure what you have stored in each of those child nodes, but let's say you have an unique identifier about that blog post such a title. Then you can use it to fetch that node and get the key:

blogRef.orderByChild("title").equals(blogTitle)

However, I am assuming you have already fetched the data to display it so you won't need to do this again. Instead when you fetch the data, add the ID of that blog in it's object. Let's say your class looks like:

public class Blog {

    public String title;
    public String key;

    //public Blog() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    //}

    public Blog(String title, String key) {
        this.title = title;
        this.key = key;
    }
}

The key here would be the node key which you can get by dataSnapshot.getKey(). When it comes to delete it, you can easily get it from the object.

Upvotes: 0

Related Questions