Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 用刷子从recyclerView和sqliteDb中删除项目_Android_Android Recyclerview - Fatal编程技术网

Android 用刷子从recyclerView和sqliteDb中删除项目

Android 用刷子从recyclerView和sqliteDb中删除项目,android,android-recyclerview,Android,Android Recyclerview,我想用刷子从recyclerView和sqlite中删除一个项目。我应该传递给dbHelper什么 我尝试使用mainAdapter.items[position]传递元素id,但它抛出元素索引8必须在[0..7]范围内的错误即使您向新安装的应用程序添加一个元素并尝试删除它,它也会抛出元素索引8必须在[0..1]范围内的错误 val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(0,ItemTo

我想用刷子从recyclerView和sqlite中删除一个项目。我应该传递给dbHelper什么

我尝试使用
mainAdapter.items[position]
传递元素id,但它抛出
元素索引8必须在[0..7]范围内的错误
即使您向新安装的应用程序添加一个元素并尝试删除它,它也会抛出
元素索引8必须在[0..1]范围内的错误

        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"
    }
}
classdbhelper(context:context):SQLiteOpenHelper(context,数据库名称,null,数据库版本){
重写onCreate(db:SQLiteDatabase?){
val CREATE_TABLE_QUERY:String=(“CREATE TABLE$TABLE_NAME($KEY_ID INTEGER主键自动递增,$KEY_TITLE TEXT,$KEY_BODY TEXT);”)
db!!.execSQL(创建表查询)
}
重写更新(db:SQLiteDatabase,旧版本:Int,新版本:Int){
db.execSQL(“如果存在,则删除表$TABLE_NAME”)
onCreate(数据库)
}
乐趣补充说明(注:注){
val db=可写数据库
val values=ContentValues()
值。放置(键标题、注释标题)
value.put(键体,注释体)
db.insert(表名称,null,值)
db.close()
}
fun getAllNotes():可变列表{
val noteList=ArrayList()
val db=可读数据库
val selectQuery=“从$TABLE\u NAME中选择*
val cursor=db.rawQuery(selectQuery,null)
如果(光标!=null){
if(cursor.moveToFirst()){
做{
val notes=注释()
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))
注释列表。添加(注释)
}while(cursor.moveToNext())
}
}
cursor.close()
db.close()
返回noteList.toMutableList()
}
项目(注:注){
val db=可写数据库
db.delete(表名称,键ID+“=?”+note.ID,null)
}
全数{
var db=可写数据库
db.delete(表名称,null,null)
}
伴星{
私有val数据库\u NAME=“note\u DATABASE.db”
专用val数据库_版本=1
专用val表\u NAME=“注释”
私有val密钥\u ID=“ID”
专用val密钥\u TITLE=“TITLE”
私有val密钥\u 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)
    }
}
class MainAdapter(变量项:MutableList,val回调:callback):RecyclerView.Adapter(){
重写CreateViewHolder(父级:ViewGroup,viewType:Int)=
主支架(LayoutInflater.from(parent.context)。充气(R.layout.item_note,parent,false))
重写getItemCount()=items.size
覆盖BindViewHolder(支架:主支架,位置:Int){
持有者绑定(项目[位置])
}
趣味getItem(位置:Int):注意{
返回项目。获取(位置)
}
接口onNoteListner{
有趣的点击(位置:Int)
}
内部类MainHolder(itemsView:View):RecyclerView.ViewHolder(itemsView){
private val title=itemsView.findviewbyd(R.id.fieldItem_title)
private val body=itemsView.findviewbyd(R.id.fieldItem_body)
趣味绑定(项目:注){
title.text=item.title
body.text=item.body
itemView.setOnClickListener{
如果(adapterPosition!=RecyclerView.NO_POSITION)callback.OnItem已单击(项[adapterPosition])
}
}
}
接口回调{
已单击(项目:注释)
}
}
尝试删除单个项目时,错误为: 您应该:

  • 从数据库中删除该项
  • 从适配器项目列表中删除该项目
  • 在适配器实例上调用notifyItemRemoved(itemPosition)

  • 这将删除该项目,并触发删除动画。

    而不是此(mainAdapter作为mainAdapter)。removeItem(viewHolder,container.context)从列表中删除项目(已传递给适配器)并调用adapter.notifyItemRemoved(position)@KishanMaurya它不起作用,可能我没有将元素传递给dbHelper进行删除?我是这样传递的:dbHelper.delete(mainAdapter.getItem(position.id)var item=yourList[position]首先从列表中删除项,然后通知适配器,然后调用DB dbHelper.delete(item.id)希望获得此帮助,否则共享您的代码,我将调试更多。没有成功。我添加代码适配器和dbHelperIt没有帮助您如何从适配器项目列表中删除该项目?(mainAdapter作为mainAdapter)。removeItem(viewHolder,container.context)这不是RecyclerView的工作方式。您应该删除其数据,而不是视图持有者。因此,您应该从
    var items:MutableList
    like items.removeAt(index)中删除一个项。之后,通知适配器您已使用
    adapter.notifyItemRemoved(itemPosition)
    删除了一个项目。这篇文章似乎详细解释了RecyclerView的工作原理:谢谢,我做到了。dbHelper.deleteItem(mainAdapter.getItem(viewHolder.adapterPosition))listNotes.removeAt(viewHolder.adapterPosition)mainAdapter.notifyItemRemoved(viewHolder.adapterPosition)