Home > Net >  MainActivity as a controller
MainActivity as a controller

Time:06-18

I have a MainActivity that starts up Activity1. When Activity1 returns back to the MainActivity, Activity2 is started. When Activity2 returns back to the MainActivity, Activity1 is started again.

I get the following error "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly" How do you do that

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

        val intent = Intent(this@MainActivity, Activity1::class.java)
        Activity1ResultLauncher.launch(intent)
    }


    val Activity1ResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == Activity.RESULT_OK) {
            val intent = Intent(this@MainActivity, Activity2::class.java)
            Activity2ResultLauncher.launch(intent)
        }
    }

    val Activity2ResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == Activity.RESULT_OK) {
            val intent = Intent(this@MainActivity, Activity1::class.java)
            Activity1ResultLauncher.launch(intent)
        }
    }

}

CodePudding user response:

The compiler is running into an issue because of the complex relation of generic types. What it is suggesting you do to fix it is to supply the explicit property types instead of making the compiler infer them. This should fix your issue:

val Activity1ResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
    //...

val Activity2ResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
    //...

By the way, property names should start with a lowercase letter by convention.

CodePudding user response:

Why do you need the MainActivity? It seems useless rather than jump Activity1 and Activity2. Can you just put the jumping logic into onDestroy of Activity1 and Activity2.

class Activity1 {
   onDestroy() {
      jumpToActivity2();
   }
}

  • Related