Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all items from ArrayList in kotlin

Tags:

android

kotlin

I have an array list in kotlin and I want to remove all item from it, leave it as an empty array to start adding new dynamic data. i tried ArrayList.remove(index) arrayList.drop(index) but none works,

The Declaration:

var fromAutoCompleteArray: List<String> = ArrayList()

here is how I try it :

for (item in fromAutoCompleteArray){
        fromAutoCompleteArray.remove(0)
             }

I'm using the addTextChangedListener to remove old data and add new data based on user's input:

    private fun settingToAutoComplete() {
        val toAutoCompleteTextView: AutoCompleteTextView =
            findViewById<AutoCompleteTextView>(R.id.toAutoCompleteText)
        toAutoCompleteTextView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                doLocationSearch(toAutoCompleteTextView.text.toString(), 2)

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                toAutoCompleteTextView.postDelayed({
                    toAutoCompleteTextView.showDropDown()
                }, 10)
            }

        })
        val adapter = ArrayAdapter(this, android.R.layout.select_dialog_item, toAutoCompleteArray)
        toAutoCompleteTextView.setAdapter(adapter)
        toAutoCompleteTextView.postDelayed({
            toAutoCompleteTextView.setText("")
            toAutoCompleteTextView.showDropDown()
        }, 10)
    }

And here is the function that adds the data :

    private fun doLocationSearch(keyword: String, fromTo: Number) {
        val baseURL = "api.tomtom.com"
        val versionNumber = 2
        val apiKey = "******************"
        val url =
            "https://$baseURL/search/$versionNumber/search/$keyword.json?key=$apiKey"
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: okhttp3.Response) {
                val body = response.body?.string()
                println("new response is : $body")
                val gson = GsonBuilder().create()
                val theFeed = gson.fromJson(body, TheFeed::class.java)
                if (theFeed.results != null) {
                    for (item in theFeed.results) {
                        println("result address ${item.address.freeformAddress} ")
                        if (fromTo == 1) {
                            fromAutoCompleteArray = fromAutoCompleteArray + item.address.freeformAddress
                            println(fromAutoCompleteArray.size)
                        } else {
                            toAutoCompleteArray = toAutoCompleteArray + item.address.freeformAddress
                        }
                    }
                } else {
                    println("No Locations found")
                }


            }

            override fun onFailure(call: Call, e: IOException) {
                println("Failed to get the data!!")
            }
        })

    }

and as you see the line println(fromAutoCompleteArray.size) shows me if it's deleted or not, and it is always encreasing.

Also, tried to use clear() without a loop and none works:

fromAutoCompleteArray.clear()

like image 942
Ahmed Wagdi Avatar asked Sep 28 '19 13:09

Ahmed Wagdi


1 Answers

The List type in Kotlin is not mutable. If you want to cause your list to change, you need to declare it as a MutableList.

I would suggest changing this line:

var fromAutoCompleteArray: List<String> = ArrayList()

To this:

val fromAutoCompleteArray: MutableList<String> = mutableListOf()

And then you should be able to call any of these:

fromAutoCompleteArray.clear()     // <--- Removes all elements
fromAutoCompleteArray.removeAt(0) // <--- Removes the first element

I also recommend mutableListOf() over instantiating an ArrayList yourself. Kotlin has sensible defaults and it is a bit easier to read. It will end up doing the same thing either way for the most part.

It is also preferable to use val over var, whenever possible.

Update: Vals not vars, thanks for spotting that Alexey

like image 87
Todd Avatar answered Sep 28 '22 09:09

Todd