Well, I am new to Firebase and I want to have my own keys while pushing new data to database.
Problem:
FireBase.push().setValue(mapped_values);
This gives structure like below:
How can I create my own custom key there? Such as username or something.
Calling push()
will generate a key for you.
If instead you use child()
, you can determine they key/path yourself.
ref.child("Victor").setValue("setting custom key when pushing new data to firebase database");
String key="1234567sdfsf8";
//custom object
User user=new User();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").child(key).setValue(user);
As an update to the top answer, the Firebase API has been changed and setValue()
does not work anymore. Now you must use the set()
function instead:
ref.child("Victor").set("setting custom key when pushing new data to firebase database");
You can create a custom key using setValue() even if the root contains many children for example if 'Users' is the root and you want to add users with email as a key it will be like this
firebase.child("firebase url").child("Users").child("user_1 email").setValue(...)
firebase.child("firebase url").child("Users").child("user_2 email").setValue(...)
etc
let's say your db look like
"BookShelf" : {
"book1" : {
"bookName" : "book1_push"
...
}
your code to be (don't use push(), push() generate a random key)
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Book data = new Book();
mDatabase.child("BookShelf").child("book1").setValue(data);
If you are using FirebaseUI :
private static final CollectionReference usersCollection = FirebaseFirestore.getInstance().collection("users");
User user = new User("MyUsername", "MyPictureUrl");
String userKey = "1234567sdfsf8";
usersCollection.document(userKey).set(user); //MAGIC LINE
In POST request it will generate ID's but in PATCH, PUT request it will mention the key which will be provided by you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With