0

I'm working on application and I want to select from table all records where attribute type is equal to for example.

I used this query

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

in adapter in getItemCount() and it returns 2 which is true so it works but when i try it in onBindViewHolder it doesn't move at all, it stays at only one record.

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

Originally it was

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

if it's like this it returns all the records

I tried cursor.moveToNext() in many places with no result.

General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

0

OK I GOT IT ! If someone needs it, I've added cursor.moveToPosition(position) after first if statement

  • This should work, but is not very efficient, as it will execute the query for each view item. Okay, you have only 2 records, but if you had more, then you should load the data into a collection (in onViewCreating or whatever) and then take them from the collection in onBindViewHolder. – Olivier Jacot-Descombes Sep 03 '21 at 12:15