Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "-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() );
        }
    });
like image 228
Sattar Avatar asked May 07 '16 23:05

Sattar


4 Answers

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.

like image 180
Samuel Robert Avatar answered Sep 28 '22 06:09

Samuel Robert


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());  } 
  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        }   });  } 
like image 34
Sattar Avatar answered Sep 28 '22 05:09

Sattar


When you fire a Firebase query there can potentially be multiple results. So when you ask for the value of a query, Firebase returns a list of items. Even if there is only one matching item, it will be a list of one item.

So you will have to handle this list in your code:

users.orderByChild("email").equalTo("[email protected]").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            Log.d("User key", child.getKey());
            Log.d("User ref", child.getRef().toString());
            Log.d("User val", child.getValue().toString());
        }
    }
like image 26
Frank van Puffelen Avatar answered Sep 28 '22 06:09

Frank van Puffelen


In Java - Android Studio, you can get the unique pushed ID as the item is written to the db...

Per "Firebase's: Save Data on Android": You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.

To get the reference at write time, instead of loading DATA with a single push()...

  • use push() to create a blank record in the database, return value is the record's reference.
  • use .getKey() to get the Key for that record.
  • use .setValue(DATA) to fill in the blank record

here's an example:

    FirebaseDatabase fb_db_instance = FirebaseDatabase.getInstance(); 
    DatabaseReference db_ref_Main = fb_db_instance.getReference("string_db_Branch_Name");

    hashMap_record = new HashMap<String, String>();           //some random data 
    hashMap_record.put("key_Item1", "string_Item1");
    hashMap_record.put("key_Item2", "string_Item2");

    DatabaseReference blankRecordReference = db_ref_Main ;   

    DatabaseReference db_ref = blankRecordReference.push();   //creates blank record in db
    String str_NEW_Records_Key = db_ref.getKey();             //the UniqueID/key you seek
    db_ref.setValue( hashMap_record);                         //sets the record 
like image 20
WM1 Avatar answered Sep 28 '22 05:09

WM1