【问题标题】:Cursor doesn't change record光标不改变记录
【发布时间】:2021-11-01 03:21:25
【问题描述】:

我正在研究应用程序,我想从表中选择属性类型等于例如 2 的所有记录 我使用了这个查询

val cursor = db.query(TableInfo2.TABLE_NAME, null, TableInfo2.TABLE_COLUMN_TYPE+" LIKE ?", arrayOf("2"), null, null, null)

getItemCount() 的适配器中,它返回 2 这是真的,所以它可以工作 但是当我在onBindViewHolder 中尝试它时,它根本不动,它只停留在一条记录上。

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        val cursor = db.query(TableInfo2.TABLE_NAME, null, TableInfo2.TABLE_COLUMN_TYPE+" LIKE ?", arrayOf("2"), null, null, null)
        if(cursor.moveToFirst()) {
            if(cursor.getString(1)=="option")
            {
                holder.imgM.setImageURI(cursor.getString(5).toUri())
                holder.imgM.setOnClickListener {
                    val intent = Intent(context, AddNewFood::class.java)
                    context.startActivity(intent)
                }
            }else{
                holder.imgM.setImageURI(cursor.getString(5).toUri())
                holder.imgM.setOnClickListener {
                    val dialog = DialogPopUp(cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(5).toUri())
                    val manager = (context as AppCompatActivity).supportFragmentManager
                    dialog.show(manager, "customDialog")
                }
                holder.imgM.setOnLongClickListener(object: View.OnLongClickListener{
                    override fun onLongClick(p0: View?): Boolean {
                        MainActivity.position = position + 1
                        MainActivity.check2 = true
                        val intent = Intent(context, AddNewFood::class.java)
                        context.startActivity(intent)
                        return false
                    }
                })
            }
        }
    }

原来是这样

val cursor = db.query(
            TableInfo2.TABLE_NAME, null, BaseColumns._ID + "=?", arrayOf(
                holder.adapterPosition.plus(
                    1
                ).toString()
            ), null, null, null
        )

如果是这样,它会返回所有记录

我在很多地方都试过cursor.moveToNext(),但没有结果:/ 请帮忙!

【问题讨论】:

标签: android sqlite android-recyclerview cursor adapter


【解决方案1】:

好的,我明白了! 如果有人需要,我加了cursor.moveToPosition(position) 在第一个 if 语句之后

【讨论】:

  • 这应该可行,但效率不高,因为它将为每个视图项执行查询。好的,您只有 2 条记录,但如果您有更多记录,那么您应该将数据加载到一个集合中(在 onViewCreating 或其他中),然后从 onBindViewHolder 中的集合中取出它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 2019-12-22
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
相关资源
最近更新 更多