Search code examples
xmlkotlinbuttonandroid-activity

Kotlin button causing crash when trying to switch activity?


I am trying to use a button to go to from a sign in page to a register page but for some reason it isn't working. From my understanding this process should be relatively simple but for some reason the action doesn't function as hoped.

I've tried using intent as I have for other pages but it just crashes the app (see Example 1). I do have another function on the same page using intent, is this an issue.

Example 1

        val goToRegisterButton = findViewById<Button>(R.id.goToRegisterButton)
        goToRegisterButton.setOnClickListener {
            Toast.makeText(this, "Button Click!", Toast.LENGTH_SHORT).show()
            val regIntent = Intent(this, RegisterActivity::class.java)
            startActivity(regIntent)
        }

I then tried calling a function which would do thintent side of things but again no luck (See Example 2).

Example 2

        val goToRegisterButton = findViewById<Button>(R.id.goToRegisterButton)
        goToRegisterButton.setOnClickListener {
            Toast.makeText(this, "Button Click!", Toast.LENGTH_SHORT).show()
            goRegisterActivity()
            
        }
    private fun goRegisterActivity() {
        Log.i(TAG, "goRegisterActivity")
        val regIntent = Intent(this, RegisterActivity::class.java)
        startActivity(regIntent)
    }

Edit: I was asked to add the stack trace, I think this is it. stack trace of issue


Solution

  • What's actually crashing? The Activity containing the button, or RegisterActivity after you click the button? Your error (please post the stacktrace as text in a code block next time! No text as images) says an Activity is failing to start because of an attempt to call findViewById before a Window, and that implies you're doing it at construction time, in a top-level variable like this:

    class SomeActivity : AppCompatActivity() {
        val badIdea = findViewById<Whatever>(R.id.some_id)
    }
    

    You can't do that because you don't have a view hierarchy until setContentView is called (so there's no view to find), and at construction time you don't have a Context to even call it on, which is why you're getting a crash. View lookups have to be done in onCreate or later, when your Activity is associated with a Context