Smeekheff
Smeekheff

Reputation: 253

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.

Upvotes: 6

Views: 3332

Answers (1)

Nick Felker
Nick Felker

Reputation: 11968

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);
    }

Upvotes: 6

Related Questions