Setting custom key when pushing new data to firebase database
JavaAndroidFirebaseFirebase Realtime-DatabaseFire SharpJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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");
Solution 2 - Java
String key="1234567sdfsf8";
//custom object
User user=new User();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").child(key).setValue(user);
Solution 3 - Java
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");
Solution 4 - Java
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
Solution 5 - Java
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);
Solution 6 - Java
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
Solution 7 - Java
In POST request it will generate ID's but in PATCH, PUT request it will mention the key which will be provided by you.
Solution 8 - Java
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
Solution 9 - Java
Simple and Fast
Map<String,Object> taskMap = new HashMap<>();
taskMap.put("Name", name.getText().toString());
taskMap.put("km", km.getText().toString());
// taskMap.put("age", "45");
taskMap.put("Day", day.getText().toString());
mDatabaseReference.push().setValue(taskMap);
Solution 10 - Java
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.
Solution 11 - Java
If you are using Node.js to write to firebase Realtime Database here's a function:
function registerVibinScores( reference, childId, dataToWrite){
var ref = db.ref(reference); //vibinScores
usersRef = ref.child(childId);
usersRef.set(
dataToWrite
);
}
//Example to invoke it:
var vibinEntry = {
"viberId": "425904090208534528",
"person": {
"name": "kukur",
"score": 0,
"id": "425904090208534528"
},
"vibinScore": 0,
"timeOfEntry": "2021-04-19T16:59:23.077Z"
}
registerVibinScores('vibinScores/allEntries', 112, vibinEntry);