bhavs
bhavs

Reputation: 2291

writing data into firebase through an android application

I am a newbie with firebase and trying to use this as the backend for an android app to store data. The format of the data is a key,value pair.

This is the code that I am using to store the data :

Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).push();
ref.setValue(map);

Due to the push reference being used the data is getting stored like this :

-J5upSABqTLJ1Wfu-jFq  
 12345
   id: 12345
   name: abcd

Where-as I want the data to be store like this :

12345
   id: 12345
   name: abcd

I am not entirely sure if the code sample above is the right way to store data. Since I want to be able to update the existing data at a later point in time . Any suggestions ?

EDIT 1: I am thinking I need to use push so that I don't over-write the existing data in the firebase repo. I have just tried to get the data back using the getValue() method and I can only fetch data which is in MAP

EDIT 2: without using a push() method with my reference I can see that the any previous data is getting overwritten and only the latest information is available. I am wondering if they is a better way to obtain the reference and still maintain the previous information

Upvotes: 7

Views: 10916

Answers (1)

hiattp
hiattp

Reputation: 2336

So it looks like you have your own system of unique ids, in which case you shouldn't need to use the .push method (that is just a helper to get a unique ref for new data). So instead of push you should be able to do:

Map<Integer, PersonData> map = new HashMap<Integer, PersonData>();
map.put(PersonData.getID(), new PersonData("abcd", 12345));
Firebase ref = new Firebase(url).child("12345");
ref.setValue(map);

Assuming your id is "12345" and url is pointing at the location where you want to store all of your persons.

To update the data without overwriting, your ref would be:

Firebase ref = new Firebase(url).child("12345");

And instead of using .setValue you would want to use ref.updateChildren(updates). You can see how to structure the updates from the example in the docs:

Map<String, Object> updates = new HashMap<String, Object>();
updates.put("first", "Fred");
updates.put("last", "Swanson");
nameRef.updateChildren(updates);

Upvotes: 15

Related Questions