【问题标题】:SearchView does not show suggestionsSearchView 不显示建议
【发布时间】:2019-09-26 21:20:18
【问题描述】:

所以我想在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


    【解决方案1】:

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

    temp[1] = city[i]
    

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

    由于i 是循环变量,而您正在循环dataset,这很可能是一个错误。不能保证数据集中的每个字符串都与数据集本身一样长。想象一下,您有一个包含一千个城市的列表;很有可能每个城市的名称都少于一千个字符。

    【讨论】:

    • 是的,我在同一行得到了错误。但是为什么我不明白。如果它包含字符串然后添加到光标,则代码在做什么。如果我这样做temp[1] = city,那么所有列表都会显示在建议中。
    • 嗯,它现在正在做的是将城市名称的i-th 字符添加到光标上。如果您只使用city,那么它会将城市名称添加到光标。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 2016-03-09
      • 1970-01-01
      相关资源
      最近更新 更多