2

Possible Duplicate:
Android: How to declare global variables?

I want to access public instance variable in main activity from other activity. And I want to call public method in main activity. How can I do that?

class MainActivity extends Activity {
    public int i;
    public void myMethod() {}
}

class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // How can I access variable i in MainActivity?
        // And How can I call myMethod() in MainActivity?
    }
}
Community
  • 1
  • 1
user1301568
  • 2,103
  • 4
  • 25
  • 32

5 Answers5

3

This is not recommended, as your activity class may be recycled by the system at any time.

Use preferences to store variables, or simplier : create your own Application class. This one will be available during all the application life, and you'll be able to store static variable in it.

Orabîg
  • 11,718
  • 6
  • 38
  • 58
3

You can pass it as an extra in the Intent with wich you start your new Activity.

Adam Monos
  • 4,287
  • 1
  • 23
  • 25
1

This might help you: How to declare global variables in Android?

You can use a subclass of Application, SharedPreferences or static variables.

Community
  • 1
  • 1
Aerilys
  • 1,628
  • 1
  • 16
  • 22
1

Try this

class MainActivity extends Activity {
    public int i;
void startNewA()
{
 Intent i = new Intent(getApplicationContext(), MyActivity.class);
 i.putExtra("var_name", i);
 startNewActivity(i);
}
}

class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int i = getIntent().getIntExtra("var_name", -1);
    }
}
InflexCZE
  • 722
  • 1
  • 14
  • 30
0

When you want to get and set the same variabl in more than one activity you could also use the prferences.

Mr.S
  • 94
  • 9