Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set confirm delete AlertDialogue box in kotlin

Tags:

android

kotlin

I have finished building a note app following an old tutorial. I want to set AlertDialogue box to confirm from the user if he really wish to delete a note.

This is what i did that closes the App

 override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            //inflate layout row.xml
            var myView = layoutInflater.inflate(R.layout.row, null)
            val myNote = listNotesAdapter[position]
            myView.titleTv.text = myNote.nodeName
            myView.descTv.text = myNote.nodeDes
            //delete button click
            myView.deleteBtn.setOnClickListener {
                var dbManager = DbManager(this.context!!)
                val selectionArgs = arrayOf(myNote.nodeID.toString())
                dbManager.delete("ID=?", selectionArgs)
                LoadQuery("%")

                val builder = AlertDialog.Builder(this@MainActivity)
                builder.setMessage("Are you sure you want to Delete?")
                    .setCancelable(false)
                    .setPositiveButton(
                        "Yes",
                        DialogInterface.OnClickListener { dialog, id -> [email protected]() })
                    .setNegativeButton("No", DialogInterface.OnClickListener { dialog, id -> dialog.cancel() })
                val alert = builder.create()
                alert.show()
            }

Please tell me what to do. thank you!

like image 869
Joseph Avatar asked Dec 01 '22 09:12

Joseph


1 Answers

I think here is the workflow that you want to achieve.

When users click on delete button, the app will show a confirmation dialog with format:

Message: Are you sure you want to Delete?
Action buttons: Yes, No

Yes: Delete the selected note from database
No: Dismiss the dialog

Here is the code

myView.deleteBtn.setOnClickListener {
    val builder = AlertDialog.Builder(this@MainActivity)
    builder.setMessage("Are you sure you want to Delete?")
        .setCancelable(false)
        .setPositiveButton("Yes") { dialog, id ->
            // Delete selected note from database
            var dbManager = DbManager(this.context!!)
            val selectionArgs = arrayOf(myNote.nodeID.toString())
            dbManager.delete("ID=?", selectionArgs)
            LoadQuery("%")
        }
        .setNegativeButton("No") { dialog, id ->
            // Dismiss the dialog
            dialog.dismiss()
        }
    val alert = builder.create()
    alert.show()
}
like image 60
Son Truong Avatar answered Dec 04 '22 00:12

Son Truong