Search code examples
androidkotlinfirebase-realtime-databasegeojsonlistof

How to add an item to a listof() function in Kotlin?


I have a listof() variable with a Coordinate(latitude,longitude) data class, for example this is how I initialise it:

var coordinate = listof<Coordinate>()

I would like to add latitude and longitude for each marker of a polygon by retrieving them from Firebase Database, for example:

val databaseReference = FirebaseDatabase.getInstance().getReference("polygon").child("coordinate")

databaseReference.addListenerForSingleValueEvent(object: ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    val numberOfCoor = snapshot.childrenCount.toInt()
                                        var i = 1

                                        for (n in i until numberOfCoor + 1) {
                                            val latitude = snapshot.child("coordinate$i")
                                                .child("latitude").getValue().toString().toDouble()
                                            val longitude = snapshot.child("coordinate$i")
                                                .child("longitude").getValue().toString().toDouble()
                                            coordinate.plus(Coordinate(longitude, latitude))
                             }
               }
override fun onCancelled(error: DatabaseError) {

  }
})

So from the code above, can be seen that I add each latitude and longitude by using coordinate.plus(Coordinate(longitude, latitude))

But when I download this GeoJSON file, the coordinate has no latitude and longitude.

So how to add item to a listof() function in Kotlin?

Thank you.


Solution

  • listOf returns an immutable List<out Coordinate>

    To be able to add items to the list, you can instantiate it with mutableListOf<Coordinate>