Sattar Sattar - 1 month ago 22
Android Question

Get the pushed ID for specific value in firebase android

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

Firebase

i want to retrieve "-KGdKip...." 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 picuter 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("z@m.com").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

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