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);
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);
String key="1234567sdfsf8";
//custom object
User user=new User();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").child(key).setValue(user);
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
Hope this helps.
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");
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
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");