无法从FirebaseDatabase获取密钥

时间:2017-05-02 04:08:04

标签: android firebase firebase-realtime-database

我将对象推送到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 "";
        }

    }

1 个答案:

答案 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);