简体   繁体   中英

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

I have this structure on my Database

在此处输入图像描述

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();
}

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
                        }
                }
            }
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM