Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the random id given to a firebase data

My problem is that I can't retrieve the random key generated by Firebase when saving data (I'm obliged to use that random key), for example

enter image description here

I tried to use dataSnapshot.getKey(), but it didn't work,any help will be highly appreciated. Thanks in advance

like image 437
TeachMePls Avatar asked Jul 05 '16 11:07

TeachMePls


2 Answers

According to your problem you could use this:

For Android:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("posts");
String key =  myRef.push().getKey();           //this returns the unique key generated by firebase

myRef.child(key).child("author").setValue("gracehop");//this creates the reqs key-value pair
myRef.child(key).child("title").setValue("Announcing COBOL");//this creates the reqs key-value pair

For Web Dev:

var messageListRef = firebase.database().ref('posts');
var newMessageRef = messageListRef.push();
newMessageRef.set({
 'author': 'gracehop',
 'title': 'Announcing COBOL'
});
like image 181
Pramod Garg Avatar answered Oct 19 '22 06:10

Pramod Garg


You can do this

String key = ref.push().getKey();
ref.child(key).setValue(post);

Hope this answers your question :)

Firebase - Save Data on Android

like image 27
Wilik Avatar answered Oct 19 '22 06:10

Wilik