K. Lok
K. Lok

Reputation: 35

The getKey method in Firebase does not return the exact push id generated

  edit = (EditText) findViewById(R.id.addCat);
          addCate = edit.getText().toString();
          Catcat add;
          String x = myRef.child("sfasf").push().getKey();
       add= new Catcat(addCate,x);
       myRef.push().setValue(add);

When I use this code, the String x differs from the actual push id by 1 letter at the end. Is this intentional or am I using the method wrong?

Upvotes: 0

Views: 344

Answers (1)

brandonwang
brandonwang

Reputation: 1653

You called push() twice, which leads to two different keys. There are a couple ways to push an object onto Firebase and get the key.

You can get the key first, then use the key to get and update the child.

String x = myRef.child("sfasf").push().getKey();
add = new Catcat(addCate,x);
myRef.child("sfasf").child(x).setValue(add);

Or you can first push the object then retrieve the key.

add = new Catcat(addCate,x);
DatabaseReference ref = myRef.child("sfasf").push(add)
String x = ref.getKey()

Upvotes: 1

Related Questions