微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从Room Database和RecyclerView中删除项目并更新列表

如何解决如何从Room Database和RecyclerView中删除项目并更新列表

在这里我有一个deleteButton数据库和recyclerview中删除所需的项目。在此onSetClickListener的{​​{1}}中,我调用函数deleteButton,并从deletePlayerHistory(positon)函数传递位置给用户删除的项目。

适配器类:

onBindViewHolder()

数据库

class FriendHistoryAdapter(private var friendHistoryData: List<FriendHistoryData>) :
    RecyclerView.Adapter<FriendHistoryAdapter.FriendHistoryHolder>() {

    class FriendHistoryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val textViewPlayer1: TextView = itemView.findViewById(R.id.text_view_player_one_name)
        val textViewPlayer2: TextView = itemView.findViewById(R.id.text_view_player_second_name)
        val textViewscore: TextView = itemView.findViewById(R.id.text_view_score)
        val textViewWhoWon: TextView = itemView.findViewById(R.id.text_view_player_won)
        val deleteButton: Button = itemView.findViewById(R.id.button_delete)

    }

    override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): FriendHistoryHolder {
        val itemView: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.friend_history_item,parent,false)
        return FriendHistoryHolder(itemView)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: FriendHistoryHolder,position: Int) {

        holder.textViewPlayer1.text = friendHistoryData[position].playerOneName
        holder.textViewPlayer2.text = friendHistoryData[position].playerSecondName
        holder.textViewscore.text =
            "score: ${friendHistoryData[position].playerOnescore}-${friendHistoryData[position].playerSecondscore}"
        when {
            friendHistoryData[position].playerOnescore > friendHistoryData[position].playerSecondscore ->
                holder.textViewWhoWon.text = "${friendHistoryData[position].playerOneName} won!"
            friendHistoryData[position].playerOnescore < friendHistoryData[position].playerSecondscore ->
                holder.textViewWhoWon.text =
                    "${friendHistoryData[position].playerSecondName} won!"
            else -> holder.textViewWhoWon.text = "Draw!"
        }
        holder.deleteButton.setonClickListener {
            deletePlayerHistory(position)
        }
    }

    override fun getItemCount(): Int {
        return friendHistoryData.size
    }

    private fun deletePlayerHistory(position: Int) {
        
    }
}

道:

@Database(entities = [FriendHistoryData::class],version = 1)
    abstract class FriendHistoryDatabase : RoomDatabase() {
    
        abstract fun friendHistoryDao(): FriendHistoryDao
    
        companion object {
            @Volatile
            private var instance: FriendHistoryDatabase? = null
            @Synchronized
            fun getInstance(context: Context): FriendHistoryDatabase? {
                if (instance == null) {
                    instance = Room.databaseBuilder(
                        context.applicationContext,FriendHistoryDatabase::class.java,"friend_history_database"
                    ).build()
                }
                return instance
            }
        }
    }

使用RecyclerView进行活动:

@Dao
interface FriendHistoryDao {

    @Insert
    fun addHistory(friendHistoryData: FriendHistoryData)

    @Query("SELECT * FROM friend_history ORDER BY id DESC")
    fun getWholeHistory() : List<FriendHistoryData>

    @Delete
    fun deleteHistory(friendHistoryData: FriendHistoryData)
}

数据类别:

class VsFriendHistory : AppCompatActivity() {
    private lateinit var friendHistoryWholeData: List<FriendHistoryData>
    private lateinit var friendRecyclerView: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_vs_friend_history)

        friendRecyclerView = findViewById(R.id.friend_recycler_view)
        friendRecyclerView.layoutManager = linearlayoutmanager(this)
        friendRecyclerView.setHasFixedSize(true)
        showWholeHistory()
    }

    private fun showWholeHistory() {
        class ShowWholeHistory : AsyncTask<Void,Void,Void>() {
            override fun doInBackground(vararg params: Void?): Void? {
                lateinit var friendHistoryDao: FriendHistoryDao
                val database: FriendHistoryDatabase? = application?.let {
                    FriendHistoryDatabase.getInstance(it)
                }
                if (database != null) {
                    friendHistoryDao = database.friendHistoryDao()
                }
                friendHistoryWholeData = friendHistoryDao.getWholeHistory()
                friendRecyclerView.adapter = FriendHistoryAdapter(friendHistoryWholeData)
                return null
            }

            override fun onPostExecute(result: Void?) {
                super.onPostExecute(result)
                if (friendHistoryWholeData.isEmpty()) {
                    Toast.makeText(baseContext,"No history to show",Toast.LENGTH_SHORT).show()
                }
            }
        }
        ShowWholeHistory().execute()
    }
}

请帮助我完成@Entity(tableName = "friend_history") data class FriendHistoryData( val playerOneName: String,val playerSecondName: String,val playerOnescore: Int,val playerSecondscore: Int ) { @PrimaryKey(autoGenerate = true) var id = 0 } 功能

谢谢。

解决方法

传入您的FriendHistoryAdapterfriendHistoryDao 它应该看起来像这样:

class FriendHistoryAdapter(
private var friendHistoryData: List<FriendHistoryData>,private val friendHistoryDao: FriendHistoryDao
) { ....

您删除的方法应如下所示:

  private fun deletePlayerHistory(position: Int) {
        val item = friendHistoryData[position]
        (friendHistoryData as MutableList).remove(item)
        notifyItemChanged(position)
        friendHistoryDao.deleteHistory(item)
    }

尝试告诉我是否可行

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。