我将对象推送到FirebaseDatabase
并尝试获取我刚刚推送到Firebase
的对象的键。我已经查看了Get the pushed ID for specific value in firebase android,我试图使用它,但它没有用。
DatabaseReference
onCreate
的初始化
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("People");
实际功能 -
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 "";
}
}
答案 0 :(得分:1)
您可以使用这种方式获取密钥..
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);