skip to Main Content

I am trying to get mutableList of mutableList of LatLng pairs in kotlin. Below is my code.
When the function onPauseButtonClicked()is called I get the value in locationlist variable which is mutableList of LatLng pairs.But I am not able to add the value to locationlists variable which is a mutableListOf(locationList) . The value is shown empty. What is wrong with code.


 private var locationList = mutableListOf<LatLng>()

 private var locationlists = mutableListOf(locationList)

/**
This is function where locationlists is called
*/

 private fun onPauseButtonClicked(){

        locationlists.add(locationList)

//        Toast.makeText(requireContext() ,"$locationList", Toast.LENGTH_SHORT).show()

        val c= locationlists[0]

        Toast.makeText(requireContext() ,"$c", Toast.LENGTH_SHORT).show()

}

2

Answers


  1. add will add the MutableList to the end of the list. However, when you call mutableListOf(locationList) you already put an empty MutableList as the first element. It’s easy to verify in the debugger, that your locationlists will have two elements, eventhough you only call add once.

    Therefore, the correct way would be to initialize locationlists with an empty list of MutableList

    var locationlists =  mutableListOf<MutableList<LatLng>>()
    
    Login or Signup to reply.
  2. While initializing use

    private val locationLists = MutableList<MutableList<LatLang>>(0){mutableListOf()}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search