Home > database >  Function onCreate not execute on activity start Kotlin Android
Function onCreate not execute on activity start Kotlin Android

Time:01-17

I'm new to Android development and I just started learning.

Here's my problem:

My onCreate function in activity_main works normally, it shows everything. Then he logs in and shows me the second activity and there also the onCreate function works but when I go to the third activity the onCreate function does not execute.

DashboardActivity.kt

class DashboardActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)
        val policy = ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
       sendGet()
       // sendPostRequest()
    }
fun openTest(view: View){
        setContentView(R.layout.activity_test);
    }
}

TestActivity.kt

class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        println("test")
    }
}

Could someone guide me or explain what and how? I've been sitting on this for a while, searching the internet and nothing...

I searched the internet, tried solutions, tried to create more activities, turned on debug mode by adding breakpoint and it doesn't even enter this function

CodePudding user response:

To start an Activity, you need to call the following:

startActivity(Intent(this, NextActivity::class.java))

Otherwise, onCreate(Bundle?) will not be called if you do not explicitly call the above.

So in your case, seems that you would like to get to TestActivity in openTest(View), you should have something like this:

fun openTest(view: View) {
  startActivity(Intent(this, TestActivity::class.java))
  // Calling setContentView() will not trigger another Activity
  // setContentView(R.layout.activity_test);
}
  • Related