I want to display an error message when the button is clicked while editText is empty, but the following error has occurred and cannot be resolved.
Could anyone please teach me?

Caused by: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button at com.example.calcapp.MainActivity.onCreate (MainActivity.kt: 35)
Corresponding source code
class MainActivity: AppCompatActivity (), View.OnClickListener {
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
        setContentView (R.layout.editor_layout)

        val btn1 = this.findViewById (R.id.button1) as Button // Line 35
        btn1? .let {it->it.setOnClickListener (this)}
        val btn2 = this.findViewById (R.id.button2) as Button
        btn2? .let {it->it.setOnClickListener (this)}
        val btn3 = this.findViewById (R.id.button3) as Button
        btn3? ​​.let {it->it.setOnClickListener (this)}
        val btn4 = this.findViewById (R.id.button4) as Button
        btn4? .let {it->it.setOnClickListener (this)}
// Transition to SecondActivity with onClick method
    override fun onClick (v: View?) {
        // Create an instance of Intent
        // Since the first argument of the constructor is context, the Activity itself, the second argument specifies the class of the Activity I want to transition
        val intent = Intent (this, SecondActivity :: class.java)

              // Get the EditText string and convert it to a number
              val A = editText1.text.toString (). toDouble ()
              val B = editText2.text.toString (). toDouble ()
              if (A.toString () == "" || B.toString () == "") {
                 makeText (this, "No number entered !!", Toast.LENGTH_SHORT) .show ()}
                  else {
                when (v? .id) {
                  R.id.button1->intent.putExtra ("VALUE", (A + B))
                  R.id.button2->intent.putExtra ("VALUE", (A --B))
                  R.id.button3->intent.putExtra ("VALUE", (A * B))
                  R.id.button4->intent.putExtra ("VALUE", (A/B))
        // Transition by calling the startActivity method with the generated Intent as an argument
        startActivity (intent)
  • Answer # 1

    Perhaps the element of R.id.button1 is in the layout of R.layout.activity_main.
    Since I have read setContentView twice, it seems that the contents of R.layout.activity_main have been overwritten by R.layout.editor_layout.

          setContentView (R.layout.activity_main)
            setContentView (R.layout.editor_layout)