Home > Net >  How to delete selected item from RoomDB
How to delete selected item from RoomDB

Time:04-09

I want to create a To-Do app, where you can add, edit and delete notes. So my question is, how can I delete item selected with checkBox from database? App doesn't crash but only Toast message appears nothing else happens. Here is my code.

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)
}

CodePudding user response:

You can do it like this:

@Query("delete from task_table where id=:userId")
fun deleteFromDatabase(userId: String)

Then call the function like this:

fun deleteFromDatabase(user: data){
        addTaskDao.deleteFromDatabase(user.id) // use your field name for id
    }

CodePudding user response:

To delete the particular item from the Db you can use the custom query like below instead of using the @Delete annotation and make sure you are calling the function in background thread

@Query("delete from task_table where id=:user.id")
  • Related