I am using first time using firebase database. I don't know how to generate unique id firebase.
Asked
Active
Viewed 1.7k times
2 Answers
8
You can use push().getKey()
to get the unique key
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("quiz").push().getKey();

Anisuzzaman Babla
- 6,510
- 7
- 36
- 53
-
Will key create a totaly random id? – Jul 20 '19 at 03:17
-
Yes. It is a random id. – Anisuzzaman Babla Jul 20 '19 at 08:11
1
As I see in your database, you have already used the push()
method to generate a unique key for your quiz object. If you want, you can use for your quizid
property the same key. So your database will look like this:
Firebase-root
|
--- quiz
|
--- -LlC8 ... XwOe
|
--- quizid: "-LlC8 ... XwOe"
|
--- //Other details
To actually get the key, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference quizRef = rootRef.child("quiz");
String key = quizRef.push().getKey();
Having this key
, you can use it to set the quizid
when adding quiz objects to the database.
If don't want to use the pushed id, there is also another approach which isthe UUID which can help you generate unique keys for your quizid
property.

Alex Mamo
- 130,605
- 17
- 163
- 193