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

时间:2020-09-22 16:55:58

标签: android database kotlin android-recyclerview android-room

在这里,我有一个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 } 功能。

谢谢。

1 个答案:

答案 0 :(得分: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)
    }

尝试告诉我是否可行