-2

I have two activities, Activity1 and Activity2.

Activity1.kt

class Activity1: AppCompatActivity {
   private val activity2 = Activity2()

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

       activity2.testLambda = {
            println("Should be called" + it)
        }
  }
} 

Activity2.kt

class Activity2: AppCompatActivity {
   var testLambda: ((String) -> Unit)? = null

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        testLambda?.invoke("Hello")
   }

}

activity2 was popup by pressing a button in Activity1:

binding.button.setOnClickListener {
        val intent = Intent(this, Activity2::class.java)
        startActivity(intent)
}

For some reason, in Activity2, onCreate, the testLambda is null. Any hints?

Thanks!

William Hu
  • 15,423
  • 11
  • 100
  • 121

2 Answers2

2

In Android a class that extends AppCompatActivity, Activity or FragmentActivity or anything similar, these classes have different life cycle than typical usual classes and you can't just instantiate them like

private val activity2 = Activity2()

You have to use intents for instantiating such activities. more info here

Moreover to keep it simple for you, At one time only one activity can be in resumed state and can be interacted with. So you can't have two activities side by side in a live state and pass data around.

There are a couple of ways to achieve what you are trying to do but that depends on what exactly you want. explain your use-case and I will update the answer more specific answer but here are more broad approaches you can use.

1) Passing data through intents

2) Use of a singleton i.e Kotlin object classes

3) Shared ViewModels using dependency injection (this is much more complicated so I wouldn't advise this if you are a beginner)

Atiq
  • 14,435
  • 6
  • 54
  • 69
1

but... it is null

var testLambda: ((String) -> Unit)? = null

opening Activity by Intent will create new instance with new testLambda

val intent = Intent(this, Activity2::class.java)
startActivity(intent)

testLambda isn't static field, so it will be null...

also: don't never ever create Activity by just calling new Activity/constructor or any other "usual" language way (like you do in Activity1). use Intent always, pass data through Bundle

snachmsm
  • 17,866
  • 3
  • 32
  • 74