Zohab Ali
Zohab Ali

Reputation: 9544

How to get previous activity in android Kotlin

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

Answers (3)

Sergio
Sergio

Reputation: 30625

  1. 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.

  2. 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)
    
  3. 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

Exigente05
Exigente05

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

AskNilesh
AskNilesh

Reputation: 69681

Now as how can I access the instance of MainActivity inside DepositActivity

AFAIK That is not possible to access instance of one activity in other Activity

if you have this type of requirement than Try to manage using Fragments

Upvotes: 3

Related Questions