如何从 RoomDB 中删除选定的项目
How to delete selected item from RoomDB
我想创建一个待办应用程序,您可以在其中添加、编辑和删除笔记。所以我的问题是,如何从数据库中删除使用 checkBox
选择的项目?应用程序没有崩溃,但只出现 Toast
消息,没有其他任何事情发生。这是我的代码。
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val rotateOpen: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_open_anim) }
private val rotateClose: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_close_anim) }
private val fromBottom: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.from_bottom_anim) }
private val toBottom: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.to_bottom_anim) }
private var clicked = false
private var dialogView: View? = null
private lateinit var mTaskViewModel: TaskViewModel
private val adapter by lazy { TaskRecycleAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
add_btn?.setOnClickListener {
onAddButtonClicked()
}
edit_btn?.setOnClickListener {
Toast.makeText(this, "Edit Button Clicked", Toast.LENGTH_SHORT).show()
}
delete_btn?.setOnClickListener {
if (!clicked || checkBox!!.isChecked) {
getPosition()
Toast.makeText(this, "usunięto notatkę", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Zaznacz Notatkę którą chcesz usunąć", Toast.LENGTH_SHORT).show()
}
}
add_task_btn.setOnClickListener {
showDialog()
}
getPosition()
recycleTask.layoutManager = LinearLayoutManager(this)
recycleTask.adapter = adapter
mTaskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
mTaskViewModel.readAllData.observe(this) { user ->
adapter.setData(user)
}
}
private fun getPosition() {
adapter.setOnItemClickListener(object : TaskRecycleAdapter.OnItemClickListener{
override fun onItemClick(position: Int) {
mTaskViewModel.deleteFromDatabase(adapter.getTaskAt(position))
}
})
}
private fun showDialog() {
dialogView = layoutInflater.inflate(R.layout.task_add_dialog, null)
val dialog = Dialog(this)
val task = dialogView?.findViewById<EditText>(R.id.taskAdd)
val taskDescription = dialogView?.findViewById<EditText>(R.id.taskDescriptionAdd)
dialogView?.findViewById<Button>(R.id.add_data_btn)?.setOnClickListener {
if(task?.text?.isEmpty() == true || taskDescription?.text?.isEmpty() == true){
Toast.makeText(this, "Dodaj poprawne dane", Toast.LENGTH_LONG).show()
}else{
val addTaskToDatabase = task?.text.toString()
val addTaskDescToDatabase = taskDescription?.text.toString()
val taskAddToDatabase = data(
0,
addTaskToDatabase,
addTaskDescToDatabase
)
mTaskViewModel.addTask(taskAddToDatabase)
Toast.makeText(this, "Dodano!", Toast.LENGTH_SHORT).show()
}
}
dialog.setContentView(dialogView!!)
dialog.show()
}
private fun onAddButtonClicked() {
setVisibility(clicked)
setAnimation(clicked)
clicked = !clicked
}
private fun setVisibility(clicked: Boolean) {
if (!clicked){
edit_btn.visibility = View.VISIBLE
delete_btn.visibility = View.VISIBLE
add_task_btn.visibility = View.VISIBLE
}else{
edit_btn.visibility = View.INVISIBLE
delete_btn.visibility = View.INVISIBLE
add_task_btn.visibility = View.INVISIBLE
}
}
private fun setAnimation(clicked: Boolean) {
if(!clicked){
add_btn.startAnimation(rotateOpen)
edit_btn.startAnimation(fromBottom)
delete_btn.startAnimation(fromBottom)
add_task_btn.startAnimation(fromBottom)
}else{
add_btn.startAnimation(rotateClose)
edit_btn.startAnimation(toBottom)
delete_btn.startAnimation(toBottom)
add_task_btn.startAnimation(toBottom)
}
}
}
TaskRecyclerAdapter.kt
class TaskRecycleAdapter: RecyclerView.Adapter<TaskRecycleAdapter.MyViewHolder>() {
private var list = emptyList<data>()
private lateinit var mListener : OnItemClickListener
class MyViewHolder(binding: TaskHolderBinding, listener: OnItemClickListener): RecyclerView.ViewHolder(binding.root) {
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: OnItemClickListener) {
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(TaskHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false), mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = list[position]
holder.itemView.findViewById<TextView>(R.id.task).text = item.task
holder.itemView.findViewById<TextView>(R.id.taskDescription).text = item.task_Details
}
override fun getItemCount(): Int {
return list.size
}
fun setData(newList: List<data>) {
val diffUtil = DiffUtil(list, newList )
val diffResults = calculateDiff(diffUtil)
list = newList
diffResults.dispatchUpdatesTo(this)
}
fun getTaskAt(position: Int): data {
return list[position]
}
}
Repository.kt
class Repository(private val addTaskDao: taskDao) {
val readAllData: LiveData<List<data>> = addTaskDao.readAllData()
suspend fun addTask(user: data){
addTaskDao.addTask(user)
}
fun deleteFromDatabase(user: data){
addTaskDao.deleteFromDatabase(user)
}
}
TaskDao.kt
@Dao
interface taskDao {
@Insert
suspend fun addTask(user: data)
@Query("Select * From task_table order by id asc")
fun readAllData(): LiveData<List<data>>
@Delete
fun deleteFromDatabase(user: data)
}
要从 Db 中删除特定项目,您可以使用如下所示的自定义查询而不是使用 @Delete 注释,并确保您在 后台线程
@Query("delete from task_table where id=:user.id")
你可以这样做:
@Query("delete from task_table where id=:userId")
fun deleteFromDatabase(userId: String)
然后像这样调用函数:
fun deleteFromDatabase(user: data){
addTaskDao.deleteFromDatabase(user.id) // use your field name for id
}
我想创建一个待办应用程序,您可以在其中添加、编辑和删除笔记。所以我的问题是,如何从数据库中删除使用 checkBox
选择的项目?应用程序没有崩溃,但只出现 Toast
消息,没有其他任何事情发生。这是我的代码。
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val rotateOpen: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_open_anim) }
private val rotateClose: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_close_anim) }
private val fromBottom: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.from_bottom_anim) }
private val toBottom: Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.to_bottom_anim) }
private var clicked = false
private var dialogView: View? = null
private lateinit var mTaskViewModel: TaskViewModel
private val adapter by lazy { TaskRecycleAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
add_btn?.setOnClickListener {
onAddButtonClicked()
}
edit_btn?.setOnClickListener {
Toast.makeText(this, "Edit Button Clicked", Toast.LENGTH_SHORT).show()
}
delete_btn?.setOnClickListener {
if (!clicked || checkBox!!.isChecked) {
getPosition()
Toast.makeText(this, "usunięto notatkę", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Zaznacz Notatkę którą chcesz usunąć", Toast.LENGTH_SHORT).show()
}
}
add_task_btn.setOnClickListener {
showDialog()
}
getPosition()
recycleTask.layoutManager = LinearLayoutManager(this)
recycleTask.adapter = adapter
mTaskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
mTaskViewModel.readAllData.observe(this) { user ->
adapter.setData(user)
}
}
private fun getPosition() {
adapter.setOnItemClickListener(object : TaskRecycleAdapter.OnItemClickListener{
override fun onItemClick(position: Int) {
mTaskViewModel.deleteFromDatabase(adapter.getTaskAt(position))
}
})
}
private fun showDialog() {
dialogView = layoutInflater.inflate(R.layout.task_add_dialog, null)
val dialog = Dialog(this)
val task = dialogView?.findViewById<EditText>(R.id.taskAdd)
val taskDescription = dialogView?.findViewById<EditText>(R.id.taskDescriptionAdd)
dialogView?.findViewById<Button>(R.id.add_data_btn)?.setOnClickListener {
if(task?.text?.isEmpty() == true || taskDescription?.text?.isEmpty() == true){
Toast.makeText(this, "Dodaj poprawne dane", Toast.LENGTH_LONG).show()
}else{
val addTaskToDatabase = task?.text.toString()
val addTaskDescToDatabase = taskDescription?.text.toString()
val taskAddToDatabase = data(
0,
addTaskToDatabase,
addTaskDescToDatabase
)
mTaskViewModel.addTask(taskAddToDatabase)
Toast.makeText(this, "Dodano!", Toast.LENGTH_SHORT).show()
}
}
dialog.setContentView(dialogView!!)
dialog.show()
}
private fun onAddButtonClicked() {
setVisibility(clicked)
setAnimation(clicked)
clicked = !clicked
}
private fun setVisibility(clicked: Boolean) {
if (!clicked){
edit_btn.visibility = View.VISIBLE
delete_btn.visibility = View.VISIBLE
add_task_btn.visibility = View.VISIBLE
}else{
edit_btn.visibility = View.INVISIBLE
delete_btn.visibility = View.INVISIBLE
add_task_btn.visibility = View.INVISIBLE
}
}
private fun setAnimation(clicked: Boolean) {
if(!clicked){
add_btn.startAnimation(rotateOpen)
edit_btn.startAnimation(fromBottom)
delete_btn.startAnimation(fromBottom)
add_task_btn.startAnimation(fromBottom)
}else{
add_btn.startAnimation(rotateClose)
edit_btn.startAnimation(toBottom)
delete_btn.startAnimation(toBottom)
add_task_btn.startAnimation(toBottom)
}
}
}
TaskRecyclerAdapter.kt
class TaskRecycleAdapter: RecyclerView.Adapter<TaskRecycleAdapter.MyViewHolder>() {
private var list = emptyList<data>()
private lateinit var mListener : OnItemClickListener
class MyViewHolder(binding: TaskHolderBinding, listener: OnItemClickListener): RecyclerView.ViewHolder(binding.root) {
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: OnItemClickListener) {
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(TaskHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false), mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = list[position]
holder.itemView.findViewById<TextView>(R.id.task).text = item.task
holder.itemView.findViewById<TextView>(R.id.taskDescription).text = item.task_Details
}
override fun getItemCount(): Int {
return list.size
}
fun setData(newList: List<data>) {
val diffUtil = DiffUtil(list, newList )
val diffResults = calculateDiff(diffUtil)
list = newList
diffResults.dispatchUpdatesTo(this)
}
fun getTaskAt(position: Int): data {
return list[position]
}
}
Repository.kt
class Repository(private val addTaskDao: taskDao) {
val readAllData: LiveData<List<data>> = addTaskDao.readAllData()
suspend fun addTask(user: data){
addTaskDao.addTask(user)
}
fun deleteFromDatabase(user: data){
addTaskDao.deleteFromDatabase(user)
}
}
TaskDao.kt
@Dao
interface taskDao {
@Insert
suspend fun addTask(user: data)
@Query("Select * From task_table order by id asc")
fun readAllData(): LiveData<List<data>>
@Delete
fun deleteFromDatabase(user: data)
}
要从 Db 中删除特定项目,您可以使用如下所示的自定义查询而不是使用 @Delete 注释,并确保您在 后台线程
@Query("delete from task_table where id=:user.id")
你可以这样做:
@Query("delete from task_table where id=:userId")
fun deleteFromDatabase(userId: String)
然后像这样调用函数:
fun deleteFromDatabase(user: data){
addTaskDao.deleteFromDatabase(user.id) // use your field name for id
}