Reputation: 2959
I am saving some data in FirebaseDatabase
under a child as a key:value
pair.
The problem is that data is getting saved as pushed, like if data1
is saved already than data2
will get saved below it. I want to save it above this already saved data.
Here is the data structure:
- branch
- child
- uniqueKey1: data1
- uniqueKey2: data2
I am saving the data using this code:
String key = mDatabase.child("branch").child("child").push().getKey();
mDatabase.child("branch").child("child").child(key).setValue(data);
What I want is the structure below:
- branch
- child
- uniqueKey2: data2
- uniqueKey1: data1
How to save the newly added data above the already saved data? Please let me know.
Upvotes: 2
Views: 1668
Reputation: 68
In your firebase database, childs in a node are ordered in alphabetical order, no matter which order you save them. If you want to retrieve them later in some specific order, let's say order by date added, you might want to create a timestamp reference.
Check here: How to sort value inside a Firebase child to the rest?
Edit: a lot of answers and edited questions while writing my answer, but as others mentioned you should not worry about the order you see the data in the database, you should only care to provide the right structure to retrieve the data correctly. As I said, in the DB the childs are ordered in alphabetical order so if you insist on ordering it by date added you should figure out a way to update the key accordingly and then update the whole node.
Upvotes: 1
Reputation: 7523
I don't think the order in which you save data is important as long as you have a strategy to retrieve it correctly in your order of choice. Firebase provides API to retrieve data ordered by either key or value.
Work with Lists of Data on Android
If you just want to retrieve the record first which was added last, you can put a timestamp that accompanies your data. There are also methods that gets you last record of a collection.
Upvotes: 1
Reputation: 1286
What you are trying to do is update data1. Then what you have to do is,
Get reference of the node you want to update.
DatabaseReference ref = mDatabase.child("branch").child("child").child("data1");
then update the child node. I'm assuming there is a child name
under data1, whose value is 'Foo'. And now you want to update it 'Bar'.
Hashmap<String, String> map = new Hashmap();
map.put("name","Bar");
ref.updateChildren(map);
This is how you update a node. If you want to completely replace the node, then you can delete the node and by calling removeValue() method and pushing the data again!.
Upvotes: 0