0

please the app keeps crashing on my phone when i try to add the values of two edit text in android studio i've tried all i can changing the data types

package com.example.danculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
lateinit var addbtn: Button
lateinit var fnum: EditText
lateinit var snum: EditText
lateinit var ans: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
      addbtn=findViewById(R.id.add) as Button
        fnum=findViewById(R.id.fnum) as EditText
        snum=findViewById(R.id.snum) as EditText
        ans=findViewById(R.id.ans) as EditText
       addbtn.setOnClickListener {
           ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())

       }

    }
}
BlackDante101
  • 81
  • 2
  • 8

2 Answers2

0

Don't use setText(int) that expects a resource id but rather use setText(CharSequence). That is, convert your Int computation to result to a String:

ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())

Also, for future reference, examining the crash stacktrace should be the first step when trying to figure out what is wrong. See Unfortunately MyApp has stopped. How can I solve this?

laalto
  • 150,114
  • 66
  • 286
  • 303
0

I never used Kotlin before,but take a look at this part of code:

ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())

In this part you are sum two integer values and want to set them as text for ans while you should use a string value for ans.So you should convert this to string again:

ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())
Mehrdad
  • 92
  • 1
  • 12