繁体   English   中英

Android:如何将我搜索过的所有项目添加到RecyclerView? (TextChangeListener和房间数据库)

[英]Android: How to add every item that i've searched for to RecyclerView? (TextChangeListener and Room Database)

我想使用EditText在数据库中搜索,然后将项添加到RecylerView。 由于TextChangedListener和adapter.notifyDataSetChanged,我在添加几个项目时遇到问题。 我只能添加一个项目。 (查询需要在线程中)。 如何添加我正在搜索的每个项目?

CostDao.kt

@Dao
interface CostDAO {

    @Query("select * from cost where name like :name")
    fun getByName(name : String) : List<Cost>

在MainActivity.kt我得到了这个:


 fun Threads() {
        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence, start: Int,
                count: Int, after: Int
         ) {
            }

            override fun onTextChanged(
                s: CharSequence, start: Int,
                before: Int, count: Int
            ) {
                Thread {
                    val itemsList = db?.costDAO()!!.getByName(s.toString())

                    runOnUiThread {

                            recyclerView.adapter = MyAdapter(this@MainActivity, itemsList)
                            adapter.notifyDataSetChanged()

                    }
                }.start()
            }

            override fun afterTextChanged(s: Editable) { }

现在我只能搜索一个项目,项目显示,并在更改编辑文本后它消失,我希望它保持,我希望我搜索的每个项目自动添加到RecyclerView。

将搜索字符串包装在通配符中(它至少应该有一个尾随通配符% ):

val itemsList = db?.costDAO()!!.getByName("%" + s.toString() + "%")

通常只查询例如。 s.length() > 3 ,为了不查询单个字符; 虽然已经有3-4个字符可能会出现相关的记录集。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM