I want to reorder data in a recyclerview using drag and drop gestures, but do not know how to re order the data in the firebase database.
Firebase is not designed to be ordered based on some visible index, but rather on entries in the database when queried.
orderByChild
, orderByKey
, or orderByValue
So if you want to reorder the values in Firebase, you should give each item an 'index' value and call orderByValue('index')
A few lines of code can upgrade current database items to use this index:
int index = 0;
mDatabase.child("data").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Data data = dataSnapshot.getValue(Data.class);
index++;
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/data/" + dataSnapshot.getKey()+"/index", index);
mDatabase.updateChildren(childUpdates);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With