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?
    }
}
0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

We can also use Parcelables to pass the Plain Class
1

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

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

Comments

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);
    }
}

1 Comment

This is just good for one or two variables to share. But, I have a lot of variables to share.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.