Beniamin Ionut Dobre
Beniamin Ionut Dobre

Reputation: 210

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

Upvotes: 6

Views: 2957

Answers (2)

user8626261
user8626261

Reputation:

you can initialize the arrylist globally same as follows

var mArrayBindStages: MutableList<String> = ArrayList()

add data into array list define the adapter and set to adapter

var adapterSearch = User_Adapter_Search_Box(activity, dataList)
                val mLayoutManager = GridLayoutManager(activity, 1)
                rc_RecyclerView!!.layoutManager = mLayoutManager as RecyclerView.LayoutManager?
                rc_RecyclerView!!.adapter = adapterSearch

                adapterSearch!!.notifyDataSetChanged()

Upvotes: 2

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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?

Upvotes: 15

Related Questions