Home > Enterprise >  Adding AlertDialog makes function not work [Kotlin]
Adding AlertDialog makes function not work [Kotlin]

Time:08-30

I want to add an AlertDialog to confirm a save. But with this alertdialog it somehow doesn't work anymore and always shows the last else function in savePin (PIN must be 4 digits). When I remove the AlertDialog and just execute the savePin in the saveBtn it works just fine. No errors show up in the logcat. This is the dialog on saveBtn:

saveBtn!!.setOnClickListener{
        // Create popup dialog
        val saveDialog = AlertDialog.Builder(this)
        saveDialog.setTitle("Warning")
        saveDialog.setMessage("Confirm save")
        saveDialog.setPositiveButton("SAVE"){ _, _ -> savePin()}
        saveDialog.setNegativeButton("CANCEL") { _, _ -> }
        saveDialog.setCancelable(false)
        saveDialog.show()
    }

This is the savePin code:

private fun savePin() {
    if(editPinCode!!.text.toString() < 4.toString()){
        if(editPinCode!!.text.toString() == "0000"){
            Toast.makeText(this, "PIN cannot be 0000", Toast.LENGTH_SHORT).show()
        }else{
            if(editPinCode!!.text.isEmpty())
            {
                Toast.makeText(this,"Please enter new PIN", Toast.LENGTH_SHORT).show()
            }
            else{
                val pin = sharedPin.edit()
                pin.putString("pin", editPinCode!!.text.toString())
                Toast.makeText(this, "Successfully saved PIN", Toast.LENGTH_SHORT).show()
                pin.apply()
            }
        }
    }else{
        Toast.makeText(this,"PIN must be 4 digits", Toast.LENGTH_SHORT).show()
    }
}

Any idea's on why it always goes to the "PIN must be 4 digits"?

CodePudding user response:

You have some weird condition to check length .that is what causing it ..

if(editPinCode!!.text.toString() < 4.toString())

If you are checking length it should be .

if(editPinCode!!.text?.length >= 4)
  • Related