Ricardo Rodrigues
Ricardo Rodrigues

Reputation: 406

Adding a Object to a firebase realtime database list turns it to an HashMap. How to keep it as a List or convert it

I added a JSON to firebase realtime database and when I retrieved it it all goes smooth until I add a new element to the list through the app and it transforms it on a Hashmap.

How can I mantain it as a list.

 override fun onDataChange(p0: DataSnapshot) {

    val database = p0.getValue(ListOfGamesJavaModel::class.java)!!
    val lastUpdate = database.date
}

This works fine before I add new elements to list

val newGameRef = database.child("gamesList")
    newGameRef.child(System.currentTimeMillis().toString()).setValue(game)
    database.child("date").setValue("23-08-2019 20:32")

After that when I run the code to retrieve the list I get this error.

com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap

Can you help me retrieve it as a List

Working

database - Working

NOT WORKING

database - Not - Working

UPDATE

If I add it like this it works, but I'm trying to add a new one without knowing the list size.

val newGameRef = database.child("gamesList")
    newGameRef.child(int.toString()).setValue(game)
    database.child("date").setValue("23-08-2019 20:32")

Upvotes: 1

Views: 1363

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

The Firebase Realtime Database it always stores data as key-value pairs, with the keys being strings. In Java this translates to a Map<String,Object>. In some cases the Firebase clients are able to automatically convert the data to an array, which translates to List<Object> in your case. But in your second JSON screenshot, the client will not automatically convert the data to a List, so you'll have to do that yourself.

As Constantin commented, start by getting the Map<String, ...> from the database, and then get the list of values from that.

override fun onDataChange(p0: DataSnapshot) {
    val map = p0.getValue(MapOfGamesJavaModel::class.java)!!
    val database = map.values
    val lastUpdate = database.date
}

The MapOfGamesJavaModel is a new class you'll have to create. Alternatively you can read Map<String, GamesJavaModel>, but you may have to do some casting with generic types in that case.

To learn more the way Firebase Realtime Database works with arrays, see Best Practices: Arrays in Firebase.

Upvotes: 3

Related Questions