Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayAdapter.clear kotlin

I am trying to learn kotlin and I want to convert one of my android projects from java to kotlin. But I have a problem

override fun onResponse(call: Call<List<CitySearch>>?, response: Response<List<CitySearch>>?) {
    if(response != null && response.isSuccessful) {
        val list = response.body()
        cityAdapter.clear()
        if(list != null && !list.isEmpty()){
            cityAdapter.addAll(list)
            listView.visibility = View.VISIBLE
            recyclerView.visibility = View.GONE
            cityName.visibility = View.GONE
        }
    }
}

I get the error Operation is not supported for read-only collection at kotlin.collections.EmptyList.clear() on the line with cityAdapter.clear() I don't know how to solve it.

For all the project please check

Problematic historic version of WeatherFragment

Current Version

like image 551
Beniamin Ionut Dobre Avatar asked Sep 07 '17 14:09

Beniamin Ionut Dobre


People also ask

How do I clear an array adapter?

You should try to override the clear() method in the ServersAdapter class and add a call to the clear() method of your ArrayList if you have one. If your data is loaded into views from an array just empty it.

What is ArrayAdapter in Kotlin?

android.widget.ArrayAdapter. You can use this adapter to provide views for an AdapterView , Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner .

How do I use ArrayAdapter?

Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view. xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.


1 Answers

At this line cityAdapter = CitySearchAdapter(context, emptyList())

emptyList will gives you an immutable list (read only) so you need to use

cityAdapter = CitySearchAdapter(context, arrayListOf())

or

cityAdapter = CitySearchAdapter(context, mutableListOf<YourType>())

Mutable Collections in Kotlin

How do I initialize Kotlin's MutableList to empty MutableList?

like image 87
Pavneet_Singh Avatar answered Oct 03 '22 19:10

Pavneet_Singh