Home > Software design >  How to add an item to a listof() function in Kotlin?
How to add an item to a listof() function in Kotlin?

Time:11-05

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.

CodePudding user response:

listOf returns an immutable List<out Coordinate>

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

CodePudding user response:

The .plus method does not modify the original list. Alternatively you can use .add.

It is good practice to use mutablelist. You can add and remove elements.

var coordinate = mutableListOf<Coordinate>()
// ...
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.add(Coordinate(longitude, latitude))
    }
  }
}
  • Related