1

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.

2 Answers 2

6

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"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm doing it the same way atm but isn't there an other way? So you can directly call a method from the activity where you start the intent from instead of first checking for GetExtras() in the destination activity and then calling a method.
6

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

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.