4

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?

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Mattwalk
  • 139
  • 1
  • 3
  • 13

3 Answers3

2

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
2

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • If i restart my activity, Will it generate the same key again :) ? – Mattwalk Feb 09 '18 at 12:11
  • As I said in the answer, on restart of activity no random id will be generated. But onclick of a button a random id will be generated (in this case Im using the random id as a new record). You can add it as you like depending on your project... – Peter Haddad Feb 09 '18 at 12:11
  • My scenario is to use same key. But your solution will generate a unique key when a button is click. I think i should store parent key in some node on Firebase database else i should use some storage medium now.. – Mattwalk Feb 09 '18 at 12:18
  • In Firebase the `push()` is used to seperate records, it is random on purpose since the whole point of using it is to seperate the records in the database. what do you mean "storage medium"? – Peter Haddad Feb 09 '18 at 12:21
  • I think i should store parent key in Firebase database else i have to store it in my Sqlite database or in shared preference. – Mattwalk Feb 09 '18 at 12:27
  • I will get a major issue if I store it in my Sqlite database or in shared preference and at some point, the Sqlite or shared preference is cleared. That's why i am avoiding to use them.. – Mattwalk Feb 09 '18 at 12:37
  • yes just store it in firebase database, there really should be no problem. The push() is used to seperate records so everytime you enter a new record it is better to use push() to seperate a record. Example a record that has (name,age,email,date) then you use a push() to seperate one user from another or in any other case – Peter Haddad Feb 09 '18 at 12:40
  • yes.you right. Thanks for your help. I'll do the same. – Mattwalk Feb 09 '18 at 12:43
1

You can create a unique key in Firebase database using push() and then add child nodes under that key. Now next time when you come to that activity, first check if parent node exists or not. If the node exists, save parent node key and use it to save new child nodes.

    String strParentKey;
        DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference("Posts");
                    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot != null && dataSnapshot.exists()) {
                                // parent node exists, get parent node from datasnapshot
                              strParentKey = dataSnapshot.value().toString();
                            } else {
                               // parent node doesn't exists, generate parent node using push
                               strParentKey = FirebaseDatabase.getInstance().getReference().child("Posts").push().getKey();
                            }
                        }

                        @Override
                        public void onCancelled(final DatabaseError pDatabaseError) {
                            pOnChildCheckListener.onChildDoesntExist();
                        }
                    });

Now using the parentKey, you can add child node using that reference.

String childKey = FirebaseDatabase.getInstance().getReference("Posts").child(strParentKey).push().getKey();

Hope this will help you lead to the solution.

Srushti
  • 131
  • 7
  • Thanks, I think it is the right solution for my scenario. I was also thinking to do the same. Thanks for your help. – Mattwalk Feb 09 '18 at 12:41