Prismere
Prismere

Reputation: 19

I want to add values under same key

"locs" : {
        "-Lci8jGrXCEP-r6LBxD8" : {
          "title" : "Marriage"
        },
        "-Lci9UNW80J2Jap_UHwj" : {
          "title" : "Visit"
        }
      },

My firebase realtime database looks like this. I want to add three other values under this same push key namely latitude and longitude and address.

  mDatabase.child("users").child(mUserId).child("locs").push().child("title").setValue(text.getText().toString());

This works in first activity. In second activity I retrieve lat and long and save it in a string lat and long respectively. Now I want these two values and addr to be saved under this same key.

This is my expected result

"locs" : {
        "-Lci8jGrXCEP-r6LBxD8" : {
          "title" : "Marriage"
          "lat"   : "xxx.xxxxxx"
          "long"  : "xxx.xxxxxx"
          "addr"  : "Street 112 xxxx"
        },
        "-Lci9UNW80J2Jap_UHwj" : {
          "title" : "Visit"
          "lat"   : "xxx.xxxxxx"
          "long"  : "xxx.xxxxxx"
          "addr"  : "Street 1212 Flat 6"
        }
      },

Upvotes: 1

Views: 90

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

You'll need to do two things:

  • Make sure the second activity knows the key to update. You can do this either by passing the key along from the first activity to the next (in an intent or in shared preferences), or by looking it up in the second activity based on some other unique property that you know the value of.
  • Update the location for that key, instead of generating a new one. You do this by calling update() instead of set() and using child(key) instead of push(). So:

    Map<String, Object> values = new HashMap<String, Object>();
    values.put("title", "new updated title");
    values.put("newprop", "value of new prop");
    mDatabase.child("users").child(mUserId).child("locs").child(key).updateChildren(values);
    

Upvotes: 1

Related Questions