SearchView不显示建议

问题描述 投票:0回答:2

所以我想在现在位于工具栏内的searchView中显示建议。因此,我创建了此适配器,它似乎无法正常工作,并且该应用程序也因此错误StringIndexOutOfBoundsException

崩溃了

适配器

class SearchHitchAdapter(context: Context, cursor: Cursor) : CursorAdapter(context, cursor, false) {

    private val dataSet = arrayListOf<String>(*context.resources.getStringArray(R.array.city_states))

    override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
        val inflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        return inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false)
    }

    override fun bindView(view: View?, context: Context?, cursor: Cursor?) {
        val position = cursor!!.position
        val textView = view!!.findViewById(android.R.id.text1) as TextView
        textView.text = dataSet[position]
    }
}

[onQueryTextChange内部正在调用此函数

 private fun setUpSearchSuggestions(query: String) {

        val dataSet = getCityList()

        val columns = arrayOf("_id", "text")
        val temp = arrayOf(0, "default")
        val cursor = MatrixCursor(columns)

        for (i in 0 until dataSet.size) {

            val city = dataSet[i]

            if (city.toLowerCase(Locale.US).contains(query.toLowerCase(Locale.US))) {
                temp[0] = i
                temp[1] = city[i]
                cursor.addRow(temp)
            }
        }
        searchVIew.suggestionsAdapter = SearchAdapter(context!!, cursor)
    }

这不起作用可以有人帮助我或向我提出建议。

android kotlin searchview
2个回答
0
投票

[Exception“ StringIndexOutOfBoundsException”表示您正在访问不存在的数据。检查您的数据集是否具有正确的列表。


0
投票

您代码中的这一行看起来可疑:

temp[1] = city[i]

这与写temp[i] = city.get(i)相同:您试图从city的位置i处获取字符。

因为i是循环变量,并且您正在循环dataset,所以这很可能是一个错误。无法保证数据集中的每个字符串都与数据集本身一样长。想象一下,您有一个一千个城市的清单。每个城市的名称少于一千个字符的机会非常多。

© www.soinside.com 2019 - 2024. All rights reserved.