How to reorder data from a firebase real-time database

I want to reorder the data in recyclerview using drag and drop gestures, but don't know how to organize the data in the firebase database.

+5
source share
1 answer

Firebase is not designed to order based on some visible index, but rather for records in the database upon request .

orderByChild , orderByKey or orderByValue

So, if you want to reorder the values ​​in Firebase, you must give each element an "index" value and call orderByValue('index')


Several lines of code can update the 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); } 
+6
source

All Articles