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);
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);
Just for sharing the knowledge.
if you are using fire-sharp, you can create the custom key as follows
IFirebaseConfig config = new FirebaseConfig
{
AuthSecret = "SecretKey",
BasePath = "https://abc.firebaseio.com/",
Host = "abc.firebaseio.com/"
};
IFirebaseClient client = new FirebaseClient(config);
var obj = new Users
{
FirstName = "test",
MiddleName = "user",
LastName = "xyz"
};
SetResponse response = client.SetAsync("Profile", "YourID");//you can use Set() as well
response = client.SetAsync("Profile/YourID", obj);//you can use Set() as well
if database reference child is fixed string, new value will not add. just it will update the previous value. for example :
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
String mText = // get data from editText or set your own custom data
now if I insert data like this:
myRef.child("abc").child("cba").setValue(mText);
every time I insert data it will update my previous data. It will not add new data. Because my reference is fixed here(myRef.child("abc").child("cba")
// this one, which is always fixed).
Now change the the value of child "cba" to a random or dynamic value which will not fix. For example:
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
myRef.child("abc").child(String.valueOf(n)).setValue(mText);
In this case it will add a new value instead of updating. because this time reference is not fixed here. it is dynamic. push() method exactly do the same thing. it generates random key to maintain unique reference.
In POST request it will generate ID's but in PATCH, PUT request it will mention the key which will be provided by you.