Search code examples
androidxmlkotlinstart-activity

Start activity from other activity in Kotlin. It crashes before loading xml


In Kotlin, in loginButton.setOnClickListener function, the following codes can start ProfileActivity;

  val intent=Intent(this@LoginActivity, ProfileActivity::class.java)
                            startActivity(intent)
                            finish()

From the ProfileActivity, the following codes can start TestActivity;

 val intent=Intent(this@ProfileActivity, TestActivity::class.java)
                            startActivity(intent)
                            finish()

However, I want to start the TestActivity from the LoginActivity. So, I updated the codes by changing only the activity name and the codes are below:

 val intent=Intent(this@LoginActivity, TestActivity::class.java)
                            startActivity(intent)
                            finish()

But, the app crashes before loading activity_test.xml. Why ?

The class in the ProfileActivity.kt is;

class profileActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile)

    }
}

The class in the TestActivity.kt is;

class TestActivity : AppCompatActivity() {

    private val QUANT = false
    private val LABEL_PATH = "labels.txt"
    private val INPUT_SIZE = 224 
 
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {  
            var strResultUri: String? = null
            strResultUri = savedInstanceState.getString(strResultUri)  
          } else { 

            setContentView(R.layout.activity_test) 

            textViewResult = findViewById(R.id.textViewResult)
            textViewResult?.setMovementMethod(ScrollingMovementMethod())
        }
}
}

Solution

  • var strResultUri: String? = null
    strResultUri = savedInstanceState.getString(strResultUri)
    

    What exactly you do here? Passing null inside savedInstanceState.getString() method?

    Also, what do you mean by changing only the name? You mean you just changed the context in the following code?

    val intent=Intent(this@LoginActivity, TestActivity::class.java)
    startActivity(intent)
    finish()
    

    That code would work inside login activity for sure.

    Also, is that a typing mistake. profileActivity. That's camel case (Not an accepted convention), and you call ProfileActivity::class.java. This shouldn't work. If it's just a typo, ignore it.