I am trying to convert String to Int in try-catch block. In my case, if the button is clicked,number inside the textview will be converted from String to Int. It is working when I use OnclickListener, I don't even need to use try-catch. But for OnkeyListener, I get "numberformatexception:invalid int" error. I even tried to use try-catch. But it still shows me this error. I really don't get why it works for OnClickListener but not for OnKeyListener. Here is my code-
var ID = findViewById<EditText>(R.id.edt_id)
btn_add.setOnClickListener {
val item=Item(
Integer.parseInt(edt_id.text.toString()),
Integer.parseInt(quan.toString()),
edt_name.text.toString(),
name.toString(),
date_record.toString(),
location_record.toString(),
master_record.toString().toInt()
)
db.addItem(item)
refreshData()
edt_id.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action ==
KeyEvent.ACTION_UP) {
//Perform Code
val ii:String = ID.text.toString()
var id:Int = 0
try {
id = Integer.parseInt(ii)
println(id!!)
Integer.parseInt(quan.toString())
Integer.parseInt(record_code.toString())
println("GG")
edt_id.text.toString()
val item=Item(
id,
Integer.parseInt(quan.toString()),
edt_name.text.toString(),
name.toString(),
date_record.toString(),
location_record.toString(),
Integer.parseInt(record_code.toString())
)
db.addItem(item)
refreshData()
edt_id.text=null
edt_id.requestFocus()
true}
catch (nfe:NumberFormatException )
{ nfe.printStackTrace() }
}
false
})
if you are using Kotlin, the safest way is using toIntOrNull()
for example:
"10".toIntOrNull()
if the string is non number, it will return null instead. after this you could use elvis operator to check if the number is null, then return another value:
val number = "ten".toIntOrNull() ?: 0
// "ten" is non number, will return null instead,
// then catch the null with elvis operator ?: and fall back to default value 0
you also could make your code become more simpler, like:
val item=Item(
ID.text.toIntOrNull() ?: 0,
quan.toString().toIntOrNull() ?: 0),
edt_name.text.toString(),
name.toString(),
date_record.toString(),
location_record.toString(),
record_code.toString().toIntOrNull() ?: 0
)
db.addItem(item)
refreshData()
edt_id.text=null
edt_id.requestFocus()
true