Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
Vincent Macharia Avatar asked Dec 18 '22 16:12

Vincent Macharia


1 Answers

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.

like image 70
Shubhank Avatar answered Jan 09 '23 10:01

Shubhank