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()

以下是我的try 方式:

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!!")
            }
        })

    }

正如你所看到的,第println(fromAutoCompleteArray.size)行告诉我它是否被删除了,而且它总是在增加.

此外,try 在没有循环的情况下使用clear(),但都不起作用:

fromAutoCompleteArray.clear()

推荐答案

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.

我建议改变这一行:

var fromAutoCompleteArray: List<String> = ArrayList()

To this:

val fromAutoCompleteArray: MutableList<String> = mutableListOf()

然后您应该可以调用其中的任何一个:

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

我也推荐mutableListOf(),而不是自己实例化ArrayList.Kotlin有合理的默认值,而且更容易阅读.在很大程度上,无论哪种方式,它最终都会做同样的事情.

如果可能,最好使用valvar.

Update:VAL不是vars,谢谢你发现了Alexey

Kotlin相关问答推荐

如何在 Big Data 中使用Inc过滤器?

API迁移到Spring Boot 3后,Spring Security无法工作

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

Kotlin-elvis算子don';不使用map.get()

为什么Kotlin有次构造函数和init块?

如何在 Kotlin 中初始化 Short 数组?

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

kotlin 如何决定 lambda 中的参数名称?

具有多个不同类型来源的 LiveData

如何在 IntelliJ 中更改 Kotlin 的this property has a backing field代码编辑器突出显示?

Kotlin 无法找到或加载主类

是否可以在 kotlin 中嵌套数据类?

`DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别

在 Koin 中提供一个 Instance 作为其接口

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

launch 仅从 Kotlin 1.3 开始可用,不能在 Kotlin 1.2 中使用

用mockk验证属性设置程序吗?

如何从kotlin中的类实例化对象

类型推断失败:RecyclerViewActions.scrollTo()