Reputation: 708
How would I call a method from a different activity? In my main activity, I have a button that shows a dialog to set the difficulty level of the game. Then you click start game which starts a new activity containing a view with all the game information. I need to send the difficulty level chosen to the other activity but cannot seem to figure out how to.
Upvotes: 1
Views: 11184
Reputation: 61
Well I don't know how sound my solution is but I created a myApplication class which sub classes the Application class .
This holds the reference to the activity I wanted to call
import android.app.Application;
public class myApplication extends Application {
public PostAndViewActivity pv;
}
When the PostAndViewActivity calls the oncreate is sets the pv to point to itself.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((myApplication) getApplication()).pv = this;
Then when I want to call the method I want I just use code like this:
((myApplication) getApplication()).pv.refreshYourself();
Perhaps a bit hacky but it works..... I welcome some critisism for this ;-)
Upvotes: 6
Reputation: 13846
You could put it in the extras with the intent:
Intent StartGame = new Intent(this, StartGame.class);
StartGame.putExtra("difficulty", difficultyLevel);
startActivity(StartGame);
Then in your StartGame.class you can retrive it like this(assuming its a string):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String difficulty= extras.getString("difficulty");
}
Upvotes: 6