Prejith P
Prejith P

Reputation: 305

Firebase overwrites existing records instead of appending them

I am a bit new to Firebase and so have been playing around with to help myself get more acquainted with it. So while I was playing around with realtime databases, I was trying to append data to the JSON tree. The code is as below

mSaudi.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            count++;
            mHistory = mChildRef.child(Integer.toString(count));
            current = riyadh;
            mChildRef.setValue(riyadh);
            mHistory.push().setValue("riyadh");
        }
    });

The tree which I require is something like this:

value:   
 1: some text   
 2: some other text

But what's a actually happening is this:

value:
   1: some text

and on updation

value:
   2:some text

the previous entry gets erased

I have tried changing the references in various ways but to no avail. Any help in this regard would be appreciated.

Upvotes: 0

Views: 4867

Answers (3)

TheOska
TheOska

Reputation: 335

You can try this

mChildRef.child("2").setValue("some text");

It should be appending new item instead of overwriting them

Upvotes: 0

Janwilx72
Janwilx72

Reputation: 506

If you would like to save both values, you have to save them using a variable such as a Hashmap. If you save a string and then try save another one under the same branch, it will delete everything previously saved. So try the following

HashMap<String, String> map = new HashMap<>();
map.put("1","String");
map.put("2","String");
mHistory.push().setValue(map);

This will save both the strings without deleting one.

If you would only like to add one String

mHistory.push().child("1").setValue("Your first String");

The biggest problem with this though is that everytime you use push() you generate a random key, so you would have to save the key as a string and use it as a reference in your child.

Upvotes: 2

JMedinilla
JMedinilla

Reputation: 481

When you set a value on Firebase, it is going to replace everything in, and under the reference.

Let's say that you have a house value, with 2 childs: Color and Size.

If you want to edit only the color value, before the setValue(), you will have to change the reference you are pushing to.

If your reference was getReference().child("houses") and you push something there, it's going to replace everything there and below it. The way to do it is create a new reference (or update the previews one) like this: getReference().child("houses").child(houseKey).child("color") and push your String there.

In your example, you will need to add the field you want to change as a child before the push() method.

The other way was already told by @Janwilx72 and is getting the whole object, updating the value locally and pushing the entire object again.

Upvotes: 0

Related Questions