Reputation: 969
I'm pushing an object to FirebaseDatabase
and trying to get the key of the object that I just pushed to Firebase
. I've looked at Get the pushed ID for specific value in firebase android and I'm trying to use that but it's not working.
Initialization of DatabaseReference
in onCreate
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("People");
The actual function-
private String pushPersonToFirebase() {
Person newPerson = new Person();
String firstName = mFirstNameTextView.getText().toString();
String lastName = mLastNameTextView.getText().toString();
if(!firstName.equals("") && !lastName.equals("")) {
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setImgPath(anonymousPeople.get(indexAnon).toString());
mDatabaseRef.push().setValue(newPerson);
return mDatabaseRef.getKey(); //This always returns "People" need it to return the key of the object that was just pushed
} else {
Toast.makeText(this, "You didn't enter all fields", Toast.LENGTH_SHORT).show();
return "";
}
}
Upvotes: 0
Views: 184
Reputation: 3954
you can get key using this way..
String key = mDatabaseRef.push().getKey(); // its your key
-- code---
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setImgPath(anonymousPeople.get(indexAnon).toString());
--- code ---
mDatabaseRef..child(key).setValue(newPerson);
Upvotes: 1