Get the pushed ID for specific value in firebase android
UPDATE 1: it can obtain also by one line
String key = mDatabase.child("posts").push().getKey();
//**************************************************************//
after searching and trying a lot of things i came to 2 ways to do that . 1. first one to get the key when i upload the post to the server via this function
public void uploadPostToFirebase(Post post) {
DatabaseReference mFirebase = mFirebaseObject
.getReference(Constants.ACTIVE_POSTS_KEY)
.child(post.type);
mFirebase.push().setValue(post);
Log.d("Post Key" , mFirebase.getKey());
}
i used it in my code to get the key after i have already pushed it to node for it in my database
public void getUserKey(String email) { Query queryRef = databaseRef.child(Constants.USERS_KEY) .orderByChild(Constants.USERS_EMAIL) .equalTo(email); queryRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { //TODO auto generated } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { //TODO auto generated; } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { //TODO auto generated; } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { //TODO auto generated } @Override public void onCancelled(DatabaseError databaseError) { //TODO auto generated } }); }
You can read the key from push() without pushing the values. Later you can create a child with that key and push the values for that key.
// read the index key
String mGroupId = mGroupRef.push().getKey();
....
....
// create a child with index value
mGroupRef.child(mGroupId).setValue(new ChatGroup());
mGroupId
contains the key which is used to index the value you're about to save.