I want to call public method in main activity from other activity. How can I do that?
class MainActivity extends Activity {
public void myMethod() {}
}
How to call method in MainActivity from another activity SOLVED
Sometimes you cannot make the method static because it depends on all sort of other state in your MainActivity. Making all the depend state also static is tantamount to just making everything global and this is just not a good idea.
Also there is nothing wrong in wanting to call a non-static method on the MainActivity - it's just like one class calling another.
Here's what you do:
Your Application is shared across all your Activities (provided they are all in the same process). This application can be used to store state. Although a sensible idea would be just to store the instances of your activities and let them store their respective states, which is what we're going to do.
create your own Application subclass:
public class MyApplication extends Application
{
MainActivity mainActivity;
}
Adjust the manifest:
In MainApplication initialise MyApplication.mainActivity
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MyApplication ma = (MyApplication)getApplication();
ma.mainActivity = this;
...
in OtherActivity retrieve the MainActivity instance.
private MainActivity mainActivity;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MyApplication ma = (MyApplication)getApplication();
mainActivity = ma.mainActivity;
...
mainActivity.someMethodOnMainActivtiy();