save unique key firebase to child

Tags: , , , ,



I have a database like this

"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

"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

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);

Answer

You can do the following:

    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



Source: stackoverflow