Sundar Nivash
Sundar Nivash

Reputation: 306

How do I overwrite existing data in Firebase?

I am using Firebase for my hybrid app. I want to overwrite the existing data. But the following code generates a new unique id:

var store = ref.child(s + "/store_location");
store.push({
    "email": t1, 
    "store_name" : sname, 
    "store_id" : sid, 
    "address" : saddr, 
    "city": scity, 
    "pincode" : spincode, 
    "country" : scountry });

Upvotes: 2

Views: 3806

Answers (2)

MoonLight
MoonLight

Reputation: 557

First of all you need to know that push creates new unique id sets (automatically). refer to firebase docs to learn more Saving Data

For your case scenario you need to use updatechildren, this is used when you want to write to multiple children of a database location at the same time without overwriting other child nodes.

(am assuming s is the unique ID key here, and store_location is another child in your database for a unique id) use hash maps to map string to objects

Code is in java not kotlin (Always specify in start what language are you using) but this will still give you an idea.

DatabaseReference store=FirebaseDatabase.getInstance().getReference("your database root path here").child(s).child("store_location");

Map<String, Object> store_update= new HashMap<>();

            store_update.put("email","youremail");
            store_update.put("store_name","yourstorename");
            store_update.put("store_id","yourid");
            store_update.put("address","youraddress");
            store_update.put("city","yourcity");
            store_update.put("pincode","yourspincode");
            store_update.put("country","yourcountrycode");

store.updateChildren(store_update).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful())
                    {
                        Toast.makeText(MainActivity.this, "Data Updated",Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(MainActivity.this, "Data Update Failed",Toast.LENGTH_SHORT).show();
                    }

                }
            });

Upvotes: 0

Justinas
Justinas

Reputation: 43557

Instead of .push(), you can use .update() (or .set() when you have child) for updating information.

store.set({
    "email": t1, 
    "store_name" : sname, 
    "store_id" : sid, 
    "address" : saddr, 
    "city": scity, 
    "pincode" : spincode, 
    "country" : scountry
});

Upvotes: 2

Related Questions