Reputation: 9544
Lets say my default activity is MainActivity
and I start another activity DepositActivity
without using finish()
in MainActivity
Now how can I access the instance of MainActivity
inside DepositActivity
Upvotes: 1
Views: 3600
Reputation: 30625
If you want to retrieve some result from DepositActivity
use startActivityForResult(..., DepositActivity::class.java)
method. In MainActivity
override onActivityResult
method:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// retrieve data using 'data' variable
}
In DepositActivity
you need to set data using method setResult()
before finishing DepositActivity
.
If you want to pass some data to DepositActivity
use intent
for that, for example:
val intent = Intent(this, DepositActivity::class.java)
intent.putExtra("Extra_Name", /*Some Data*/)
startActivity(intent)
Not Recommended: Use static reference to MainActivity
(don't forget to delete it in onDestroy()
method):
class MainActivity : AppCompatActivity() {
companion object {
@SuppressLint("StaticFieldLeak")
@JvmStatic
var instance: MainActivity? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
instance = this
}
override fun onDestroy() {
instance = null
super.onDestroy()
}
}
In DepositActivity
you can access it like this:
MainActivity.instance?./* call some method or property */
But you should not rely on onDestroy()
being called, cause there are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it... So you can have memory leak
Upvotes: 1
Reputation: 2211
You need to declare as companion object variable and method in MainActivity. Static type of variables and methods are declared as companion object in Kotlin.
Look at below example,
Declare variables and methods in MainActivity,
val value : String = "hello from Main"
companion object {
lateinit var instance : MainActivity
fun getInstancem() : MainActivity {
return instance
}
}
Use this instance and print value in DepositActivity like,
Log.d("log_in_second_activity", "message " + MainActivity.getInstancem().value)
You can see log message.
Hope this will give you hint.
Upvotes: 0