Get the pushed ID for specific value in firebase android

Sattar picture Sattar · May 8, 2016 · Viewed 92.6k times · Source

I want to retrive the id that generated by firebase when I pushed value to it like next

Firebase

I want to retrieve "-KGdKiPSODz7JXzlgl9J" this id for that email I tried by getKey() but it return "users" and when user get value it return the whole object from the id to profile picture and that won't make me get it as User object in my app

how solve this ?

    Firebase users = myFirebaseRef.child("users");
    users.orderByChild("email").equalTo("[email protected]").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            dataSnapshot.getKey();
            Log.d("User",dataSnapshot.getRef().toString());
            Log.d("User",dataSnapshot.getValue().toString());
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            Log.d("User",firebaseError.getMessage() );
        }
    });

Answer

Samuel Robert picture Samuel Robert · Jan 23, 2017

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.