Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder the data from firebase real time database

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.

like image 342
Smeekheff Avatar asked Jul 01 '16 00:07

Smeekheff


1 Answers

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);
    }
like image 61
Nick Felker Avatar answered Sep 28 '22 00:09

Nick Felker