I have a database like this
JavaScript
x
"Chats" : {
"-MCzU6r-JqvAkC9unjru" : {
"isSeen" : false,
"message" : "H",
"receiver" : "wwRWdMQ62bNwO09M5LpxXks37442",
"sender" : "R5ICmEp5B6Sbhow523BmQoF6uUG2",
"timestamp" : "1595571732585",
"type" : "text"
}}
I want to save a unique key “-MCzU6r-JqvAkC9unjru” in my child, like this
JavaScript
"Chats" : {
"-MCzU6r-JqvAkC9unjru" : {
"isSeen" : false,
"message" : "H",
"receiver" : "wwRWdMQ62bNwO09M5LpxXks37442",
"sender" : "R5ICmEp5B6Sbhow523BmQoF6uUG2",
"timestamp" : "1595571732585",
"type" : "text",
"key" : "-MCzU6r-JqvAkC9unjru"
}}
can I do that? if can how I can implement it in my code?
here code for add data to firebase
JavaScript
private void sendMessage(final String message) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String timestamp = String.valueOf(System.currentTimeMillis());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", myUid);
hashMap.put("receiver", hisUid);
hashMap.put("message", message);
hashMap.put("timestamp", timestamp);
hashMap.put("isSeen", false);
hashMap.put("type", "text");
databaseReference.child("Chats").push().setValue(hashMap);
Advertisement
Answer
You can do the following:
JavaScript
String key = databaseReference.child("Chats").push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", myUid);
hashMap.put("receiver", hisUid);
hashMap.put("message", message);
hashMap.put("timestamp", timestamp);
hashMap.put("isSeen", false);
hashMap.put("type", "text");
hashMap.put("key",key);
databaseReference.child("Chats").child(key).setValue(hashMap);
Using getKey()
you can retrieve the random id created using push()
and then add it to the hashMap