Classical X Classical X - 3 months ago 58
Android Question

How to get the key dynamically in Firebase?

I have i Firebase data created like this :

enter image description here

I need to get the second object's ID. I tried to use getKey() method but its returned "Post" .. I want to get the unique ID.
I use this code to add values :

private DatabaseReference refposts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = this;
refposts = FirebaseDatabase.getInstance().getReference("Posts");
Posts posts = new Posts();
posts.setTitle("Title2");
posts.setDesc("Desc2ً");
posts.setWriter("user-1");
refposts.child("Post").push().setValue(posts);
}

Answer

Here's the solution :

            DatabaseReference ref = database.getReference("Posts/Post");

            // Attach a listener to read the data at our posts reference
            ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        Posts  post = postSnapshot.getValue(Posts .class);
                        //postSnapshot.getKey(); THIS IS YOUR UNIQUE KEY
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });

Suggestion :

Don't : refposts.child("Post").push().setValue(posts);

Do's : refposts.push().setValue(posts);

And then only use "Posts" for database reference.


To use Query :

DatabaseReference myRef= database.getReference("Posts/Post");
    Query query = myRef.orderByChild("title").equalTo("Title2");
                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
Comments