-1

what is wrong with that code?

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.randomButton.setOnClickListener {
        findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
    }

    view.findViewById<Button>(R.id.toast_button).setOnClickListener {
        val myToast = Toast.makeText(context, "Hello Toast!", Toast.LENGTH_SHORT)
        myToast.show()
    }

    view.findViewById<Button>(R.id.count_button).setOnClickListener {
        countMe(view)
    }
}

private fun countMe(view: View) {
    val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
    val countString = showCountTextView.text.toString()
    var count = countString.toInt()
    count++
    showCountTextView.text = count.toString()
}

Im doing 'Build Your First Android App in Kotlin' [ https://developer.android.com/codelabs/build-your-first-android-app-kotlin#7 ] tutorial and app is crashing when i press random button on device. There is no crash when i delete those 3 lines

    var count = countString.toInt()
    count++
    showCountTextView.text = count.toString()

but ofc it doesnt solve the problem.

Harry37
  • 7
  • 2
  • Most likely the text in the textview is not a number. But we can't tell for sure without a stacktrace. If you don't know what a stacktrace is I suggest you to read https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – Ivo Sep 02 '22 at 10:37

1 Answers1

0
var count = countString.toInt()
count++
showCountTextView.text = count.toString()

I don't know the input, but I think that you have a new line (\n) character there. Maybe you should escape special characters, that don't allow the "toInt()" conversion.

In the R.id.textview_first you can also disable non-numeric characters. That would remove unwanted characters.

Could you show us the inputString?

EndrIT
  • 65
  • 9