-1

if I have 2 Activities and I want to add if condition from a variable on the another activity How can I do that? like if i have the variable that contains 9 numbers in the first layout(first activity) and i want to set if condition in the another one using the x variable that is the question. I am using Android Studio with kotlin.

  • Well, taking variable from other activity is generally bad idea because other activity could be destroyed in the meantime. If you have variable that you want to share across activities then declare it in Application class and get them through (YourApplicationClass)getApplicationContext(). – Tuby Jun 09 '17 at 22:29
  • 1
    Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – zsmb13 Jun 10 '17 at 05:59
  • Thanks! it worked! – Mohammad Salah Jun 11 '17 at 03:45

1 Answers1

3

If the value of your variable doesn't change after you start your second activity, you can use extras to pass the value between them.

class FirstActivity : Activity() {

    var myVariable: Boolean = false

    fun gotoSecondActivity() {
        val intent = Intent(this, SecondActivity::class.java)
        intent.putExtra("MyVariable", myVariable)
        startActivity(intent)
    }
}

class SecondActivity: Activity() {
    fun getMyVariable(): Boolean {
        if (intent != null) {
            if (intent.extras != null) {
                return intent.extras.getBoolean("MyVariable")
            }
        }
        return false // default
    }
}
Nathan Reline
  • 1,137
  • 10
  • 13