5

I am trying to store data (not users) in a Firebase backend. How do I generate Firebase unique identifer and store it in the child? I have been using firebase (DatabaseReference Key) as the unique identifier of a record nut the key is null.

Carven
  • 14,988
  • 29
  • 118
  • 161
Vincent Macharia
  • 475
  • 2
  • 7
  • 20

2 Answers2

11

You can use push().getKey() to get the unique key

FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("todoList").push().getKey();

Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( key, todo.toFirebaseObject());
database.getReference("todoList").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        if (databaseError == null) {

        }
    }
});

This is explained in the docs under Update specific fields section

This example uses push() to create a post in the node containing posts for all users at /posts/$postid and simultaneously retrieve the key with getKey(). The key can then be used to create a second entry in the user's posts at /user-posts/$userid/$postid.

Denysole
  • 3,903
  • 1
  • 20
  • 28
Shubhank
  • 21,721
  • 8
  • 65
  • 83
0
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("todoList").push().getKey();

Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( key, todo.toFirebaseObject());
database.getReference("todoList").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        if (databaseError == null) {

        }
    }
});
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97