Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a unique key and use it to send data in Firebase?

I'm using Firebase in my project and I was trying to create a unique key using Firebase. Using this key I wanna send posts when user start the activity. Like this:

 "Posts"
     |
      -> "Parent Unique key"
                 |
                 -> "child unique key 1"
                 -> "child unique key 2"
                 -> "child unique key 3"
                 ...

I wanna create Parent Unique key and by using it I wanna send posts. I know how to create unique key in firebase using push() but the problem is when user restart the activity, a new unique key will generate. I don't wanna create the same parent key again after creating once and I can't use user_id here as multiple users have different ids. Also I don't wanna store the parent key in some storage medium. Is it possible to create such key in firebase?

like image 341
Mattwalk Avatar asked Oct 28 '25 13:10

Mattwalk


2 Answers

If you do this inside onCreate() method:

DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Posts").push();

then yes, everytime you enter that activity a new push id will be created. This is because push() generates a random id.

To be able to solve this, you need to add push() later on.. or under a condition but not at the beginning.

So you can add it onClick of a button:

 ref.push().child("name").setValue(name);

This way everytime you click a button it will generate a push id, not when you restart the activity.

like image 104
Peter Haddad Avatar answered Oct 31 '25 04:10

Peter Haddad


To solve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uniqueKey = rootRef.child("Posts").push().getKey();
DatabaseReference uniqueKeyRef = rootRef.child("Posts").child(uniqueKey);

So for adding data, use only uniqueKeyRef reference. So, using this code you'll create a unique id only once. You'll be able to add those childs under a single id.

If you want another key, see UUID which can help you generate unique keys for your Firebase database without having to use the push() method.

like image 23
Alex Mamo Avatar answered Oct 31 '25 02:10

Alex Mamo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!