从recyclerView和sqliteDb轻扫即可删除项目

时间:2019-10-15 09:29:36

标签: android android-recyclerview

我想通过滑动从recyclerView和sqlite中删除一个项目。我应该将什么传递给dbHelper?

我尝试使用mainAdapter.items [position]传递元素的ID,但是它抛出an Element index 8 must be in range [0..7] error即使将一个元素添加到新安装的应用程序中并尝试将其删除,它也会抛出an Element index 8 must be in range [0..1] error

        val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, position: Int) {
                    var item = mainAdapter.items[position]
                (mainAdapter as MainAdapter).removeItem(viewHolder,container.context)
                    var db = dbHelper.writableDatabase
                    Toast.makeText(context,"${item.id} + ${item.body} + ${item.title}",Toast.LENGTH_SHORT).show()
            }
        }

我的dbHelper的代码:

class dbHelper(context: Context):SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION){
    override fun onCreate(db: SQLiteDatabase?) {
        val CREATE_TABLE_QUERY:String = ("CREATE TABLE $TABLE_NAME ($KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT, $KEY_TITLE TEXT, $KEY_BODY TEXT);")
        db!!.execSQL(CREATE_TABLE_QUERY)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
        onCreate(db)
    }

    fun addNote(note: Note){
        val db = writableDatabase
        val values = ContentValues()
        values.put(KEY_TITLE,note.title)
        values.put(KEY_BODY,note.body)

        db.insert(TABLE_NAME,null,values)
        db.close()
    }

    fun getAllNotes():MutableList<Note>{
        val noteList = ArrayList<Note>()
        val db = readableDatabase
        val selectQuery = "SELECT * FROM $TABLE_NAME"
        val cursor = db.rawQuery(selectQuery,null)
        if(cursor!=null){
            if(cursor.moveToFirst()){
                do{
                    val notes = Note()
                    notes.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID)))
                    notes.title = cursor.getString(cursor.getColumnIndex(KEY_TITLE))
                    notes.body = cursor.getString(cursor.getColumnIndex(KEY_BODY))
                    noteList.add(notes)
                }while (cursor.moveToNext())
            }
        }
        cursor.close()
        db.close()
        return noteList.toMutableList()
    }

    fun deleteItem(note: Note){
        val db = writableDatabase
        db.delete(TABLE_NAME, KEY_ID + "=?"+note.id, null)
    }

    fun deleteAll() {
        var db = writableDatabase
        db.delete(TABLE_NAME,null,null)
    }

    companion object{
        private val DATABASE_NAME = "note_database.db"
        private val DATABASE_VERSION = 1
        private val TABLE_NAME = "notes"
        private val KEY_ID = "id"
        private val KEY_TITLE = "title"
        private val KEY_BODY = "body"
    }
}

我的适配器的代码:

class MainAdapter (var items: MutableList<Note>,val callback: Callback) : RecyclerView.Adapter<MainAdapter.MainHolder>(){
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MainHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_note,parent,false))

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: MainHolder, position: Int) {
        holder.bind(items[position])
    }

    fun getItem(position: Int): Note{
        return items.get(position)
    }

    interface onNoteListner{
        fun onNoteClick(position: Int)
    }

    inner class MainHolder(itemsView: View) : RecyclerView.ViewHolder(itemsView){
        private val title = itemsView.findViewById<TextView>(R.id.fieldItem_title)
        private val body = itemsView.findViewById<TextView>(R.id.fieldItem_body)

        fun bind(item: Note){
            title.text = item.title
            body.text = item.body


            itemView.setOnClickListener{
                if(adapterPosition!= RecyclerView.NO_POSITION) callback.onItemClicked(items[adapterPosition])
            }
        }
    }

    interface Callback{
        fun onItemClicked(item: Note)
    }
}

尝试移除单个项目时,错误为: https://i.stack.imgur.com/5gCeO.png

1 个答案:

答案 0 :(得分:0)

您应该:

  1. 从数据库中删除项目
  2. 从适配器项目列表中删除项目
  3. 在您的适配器实例上调用notifyItemRemoved(itemPosition)

这应该删除该项目并触发删除动画。