firebasekotlinfirebase-realtime-databasehashmaplinkedhashmap

Is there a way to retrieve realtime firebase map as a linkedhashmap or at least maintain the order it is saved in


I have a map of string boolean pairs saved on firebase realtime database and was wondering if there is a way to retrieve it in kotlin as a linkedhashmap such that the original order remains in place.

I have tried typecasting to a linkedhashmap and got an error that hashmap cannot be typecasted to linked hashmap, I then tried calling the linkedhashmap constructor method with the parameter being the data from the database as a hashmap but that does not maintain the order


Solution

  • Properties in JSON are by definition not in any specific order.

    While you can retrieve data from Firebase in a specific order, by calling one of its orderBy... operations, that order will be lost when you call .value in the DataSnapshot as DataSnapshot.value returns a Map, which is unordered again.

    If you want to retrieve the nodes in a specific order:

    1. Call orderBy... to get the nodes in a specific order.
    2. Loop over the children of the snapshot you get back to process them in order, and only call value on each specific child node.