Vincent Macharia
Vincent Macharia

Reputation: 475

How to generate firebase uid

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.

Upvotes: 5

Views: 20306

Answers (2)

Abdullah Al Shahed
Abdullah Al Shahed

Reputation: 51

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) {

        }
    }
});

Upvotes: 0

Shubhank
Shubhank

Reputation: 21805

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.

Upvotes: 11

Related Questions