In my main activity (where everything happens in my application) I call a variety as of now just two other activities which end up calling back to my MainActivity via button press. How do I distinguish between these two Intents back to my MainActivity? I have seperate operations I want to prefrom based on things I did back in the two seperate activites.
Heres what I tried:
Intent intent = getIntent();
String s_message = intent.getStringExtra(AppSettings.EXTRA_MESSAGE);
String f_message = intent.getStringExtra(ViewFavorites.EXTRA_MESSAGE);
if(s_message != null) {
//do something
} else if (f_message != null) {
//do something
}
But when I run my application I find when exiting the two activities that they are prefroming the methods I do not wish them to...am I going about this wrong?
What I do is simply set an Extra in my passing Intent then compare that. Something like this. When creating the Intent add an Extra to compare to
intent.putExtra("source", "appSettings");
then in your Activity check what that value is
Intent intent = getIntent();
String source = intent.getStringExtra("source"); // get that value here
if(s_message != null) {
if ("appSettings".equals(source)){
//do something
} else if (viewFavorites.equals(source)) {
//do something else
}
}
You could use variations of this as far as how you assign the Extra but this is a simple example that works well for me, especially when there are just a few Activites that will be calling this one.
Set a different ACTION on each intent, then use if(getIntent().getAction().equals(ACTION)) to distinguish between intents.
public class MainActivity extends Activity {
public static final String ACTION_ONE = "com.yourpackage.ACTION_ONE";
public static final String ACTION_TWO = "com.yourpackage.ACTION_TWO";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if(intent.getAction() != null){
if(intent.getAction.equals(ACTION_ONE){
//DO SOMETHING
} else if (intent.getAction.equals(ACTION_TWO){
//DO SOMETHING
}
}
}
.....
}
Then when you start your main activity with an intent:
Intent intent = new Intent(MY_CURRENT_CONTEXT, MainActivity.class); //Or MainActivity subclass
add
intent.setAction(ACTION_ONE);
or whichever action is specific to what your intent is trying to accomplish.
Related
I have an activity which can be accessed via different activities.
Like you have one activity containing a listview and the second containing a gridview and both shows the same data. When you click on an item a new activity with some details is shown. I need to somehow remember which activity was the initial one (with gridview or listview) so that I can set a button to redirect here. But it's not enough to just return to previous activity (like using finish() to close the current one), because there is a way to navigate among different objects from inside the details activity (I have a gridview on that screen). So I need to remember the initial view during moving through the details activity for various number of times.
Is there a way?
EDIT: omg why so many downvotes? At least tell me why it is so stupid, I'm learning coding for Android for 2 weeks how am I supposed to know everything??
This sounds like it would best be solved by using two Fragments within the same Activity
You can use a bundle object to pass data to the new activity (B) so you could know wich activity (listView or gridView) had started it.
In activity B:
private static final String ACTIVITY_TYPE = "activity_type";
public static Intent createIntent(Context context,String activityType)
{
Intent intent = new Intent(context, ActivityB.class);
Bundle b = new Bundle();
b.putString(ACTIVITY_TYPE,activityType);
intent.putExtras(b);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
String activityType;
if (b != null)
{
activityType = b.getString(ACTIVITY_TYPE);
}
//the calling activity didn't use the createIntent method and didn't provide the activity type
else
{
activityType = "some_default_type";
}
//save activity type to use later
//rest of your code
}
In the calling activity:
Intent intent = ActivityB.createIntent(ActivityListView.this,"activity_list_view");
startActivity(intent);
I have an Activity that uses the following code to retrieve information from another activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int tok = extras.getInt("Token");
tempToken += tok;
}
This is the Code inside the first other class that sends this information:
final Button mainMen = (Button) findViewById(R.id.toMainMenu);
mainMen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Menu.class);
i.putExtra("Token", tok + teTok);
startActivity(i);
}
});
Now i have another Activity that also wants to sen information to the Main Activity like so:
maMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Campaign.this, Menu.class);
intent.putExtra("Token", player.tokens);
intent.putExtra("Round", player.round);
intent.putExtra("Rank", player.rank);
intent.putExtra("Score", player.score);
intent.putExtra("Sec", player.secondsTapped);
intent.putExtra("Min", player.minutesTapped);
intent.putExtra("Hour", player.hoursTapped);
intent.putExtra("Day", player.daysTapped);
intent.putExtra("LifeTap", player.tapsInLife);
intent.putExtra("SecTap", player.tapsPerSec);
intent.putExtra("TapRo", player.tapps);
startActivity(intent);
}
});
Now my question is, how do i handle these different extras from multiple Activities inside the one Main Activity?
Thank You for your time :)
There are two ways to solve your problem..
1)
You can pass one boolean value to or and int variable with some value.. And retrieve this in your new Activity and check with boolean value or int value and get correct data correspond to Activity.
2) You can save your all Data in Shared Preference. And get your all Data in any Activity.
you can send one boolean value that data is in first class or second class and in MainActivity check the value and get the correct data
My question is a bit basic. I've been learning to code on JAVA and android. Here I am a bit confused on how to call the values that I have sent via an intent.
In my first activity this is the intent that I am using.
Intent intent = new Intent(MainActivity.this, Secondactivity.class);
String regName1 = regName;
intent.putExtra(regName1, regNameSplit[0]);
startActivity(intent);
Here regName1 will contain three values. SessionID,URL,Name split by "-".
In my SecondActivity
public class Secondactivity extends Activity {
public final String TAG = "###---Secondactivity---###";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Log.i(TAG,"before if statement");
if (getIntent().getStringExtra("regName1") != null){
getIntent().getStringExtra("regName1").split("-");
String[] str = "regName";
Log.i(TAG, ""+str[0]+str[1]+str[2])
}
}
}
The value if regName1 always comes as null.
This line
intent.putExtra(regName1, regNameSplit[0]);
Needs to be like this instead
intent.putExtra("regName1", regNameSplit[0]); // note the quotes
BUT you are using regName1 as a variable... how do you expect the second class to know that variable?
Use a string resource instead.
and you are sure that the content of the variable regName is actually "regName"?
cause you set the value using
intent.putExtra(regName, ... )
and you get the value using
intent.getStringExtra("regName")
use firstactivity
dont use
String regname1=regname;
just:
intent.putExtra("regName1", regNameSplit[0]);
in second Activity
if (getIntent().getStringExtra("regName1") != null){
//
}
I am new to android so please excuse the newbie question. I have a game I am trying to port from an old Java applet to android. My goal is to get this functional and then post an article on a site like CodeProject (or a better one if there are ones more appropriate). The idea is to show that a person brand new to android development can create an app in a reasonable amount of time.
I am making some progress but have run into a problem. I have the main activity in which the user interacts with. I then created a menu item that in turn starts a second activity (call it child) with a modest number of checkbox's, seekbar's etc to fill in parameters. I can successfully pass the class containing all the options from main to child. But I cannot get the child to pass this data back to the main.
First here is my main code that starts the child activity:
public void addBalls()
{
Intent myIntent = new Intent(this, GameOptions.class);
Bundle b = new Bundle();
b.putSerializable("options", gameParams);
myIntent.putExtras(b);
startActivityForResult(myIntent,STATIC_OPTIONS_VALUE);
}
The data passed to the child (and hopefully back again) is:
public class GameOptionParams implements Serializable
{
private static final long serialVersionUID = 1L;
public int speedBarPosition;
public int vgravityBarPosition;
public int mgravityBarPosition;
public int viscosityBarPosition;
public int restititionBarPosition;
public boolean trace;
public boolean collide;
public boolean mush;
public boolean wrap;
public boolean flicker;
}
And here is the expected return (again in main)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case (STATIC_OPTIONS_VALUE) :
{
if (resultCode == Activity.RESULT_OK)
{
//retrieve intended options
Bundle b = data.getExtras();
gameParams = (GameOptionParams) b.getSerializable("options");
}
break;
}
}
}
The child activity successfully receives the gameParams data. It then interacts with the user to update the values and then I attempt to return it but it does not seem to get sent to main. Here is the child code in the onStop() override.
Maybe this code should not be in the onStop() override but I can't determine where else to place it.
#Override
public void onStop()
{
super.onStop();
//read widget values
gameParams.speedBarPosition = speedBar.GetPosition();
gameParams.vgravityBarPosition = vgravityBar.GetPosition();
gameParams.mgravityBarPosition = mgravityBar.GetPosition();
gameParams.viscosityBarPosition = viscosityBar.GetPosition();
gameParams.restititionBarPosition = restititionBar.GetPosition();
//todo save to persistent
Intent resultIntent = new Intent(this, TiltBall2ImpactActivity.class);
Bundle b = new Bundle();
b.putSerializable("options", gameParams);
resultIntent.putExtras(b);
setResult(Activity.RESULT_OK, resultIntent);
}
Back in the main onActivityResult override I always see requestCode=0, resultCode=0, data=null. I assume this is a typical newbie problem, I have been reading the sdk documentation, user forums etc and have come close to a solution but just not quite there yet. Any help would be appreciated.
Since this is sort of a setting menu for the game, I assume you are going to need these values for more than one activity. If so you extend the android.app.Application class.
In that class you can create attributes to hold your values. In any activity you can call
MyApplication myApp = (MyApplication)getApplicationContext();
where myApp is a singleton. So you will get the values you set from another activity.
You will need to add this code to your application tag in the manifest file for it to work
android:name=".MyApplication"
If you need to keep these values for next startup of the application, you need to use SharedPreferences. This is a good tutorial for that
http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
Assuming in your 'child' activity, the user has to press an 'OK' or 'Save' button then put the code to set the gameParams parameters in the button's onClick(...) handler.
Use the default constructor for instantiating the Intent, example...
Intent resultIntent = new Intent();
...then after creating the Bundle and adding gameParams to it and calling setResult(...), simply call finish() to terminate the 'child' activity. There aren't many occasions that I can think of to override onStop() and I suspect you don't want to be using it to attempt returning the Intent.
I need to know a generic way to distinguish between a call of activity from launcher and a call from another activity from inside my app, or a BACK on the activity stack
Anyone? this is bugging me for quite a while now and i need to put it to rest...
Thanks in advance
JQCorreia
In the onCreate of your Activity, call getIntent(). If the Activity is started from the launcher (home screen) the values for getAction() will be android.intent.action.MAIN and the getCategories() will return a set which will contain the android.intent.category.LAUNCHER category.
If the activity is started from elsewhere these values may be null.
In addition to #advantej's answer, you can extend each start-call to that activity adding an extra to the starting intent (e.g. intent.putExtra("caller", this.getClass().getSimpleName());
In the activity's onCreate method you can check then what #advantej suggests.
If the initiator is not the home-screen icon, than you can check further if the intent.hasExtra("caller") returns true, and if so, what is it.
You can find it out from intent flag.
step 1:
Intent intent = getIntent();
int flag = intent.getFlag();
step 2:
if flag = Intent.FLAG_ACTIVITY_NEW_TASK
launch from other app or activities
else
launch from home page
in 2 cases the onRestart(); called, 1.when activity come from background, 2.when the user reach the activity by back button then sample solution:
use onBackPressed() function to set a flag.. so u know that onRestart called becouse of back button press...
in onRestart () check the flag and reset it and....
Based on advantej's answer, here is a full example that also hides the UP button if the activity was launched from a launcher icon:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
/**
* If this activity was started from launcher icon, then don't show the Up button in the action bar.
*/
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Intent intent = getIntent();
Set<String> intentCategories = intent.getCategories();
boolean wasActivityStartedFromLauncherIcon = Intent.ACTION_MAIN.equals(intent.getAction()) && intentCategories != null && intentCategories.contains(Intent.CATEGORY_LAUNCHER);
boolean showUpButton = !wasActivityStartedFromLauncherIcon;
actionBar.setDisplayHomeAsUpEnabled(showUpButton);
}
}
Here's convenience method so you don't need to write it yourself:
protected boolean isStartedByLauncher() {
if (getIntent() == null) {
return false;
}
boolean isActionMain = Intent.ACTION_MAIN.equals(getIntent().getAction());
Set<String> categories = getIntent().getCategories();
boolean isCategoryLauncher = categories != null && categories.contains(Intent.CATEGORY_LAUNCHER);
return isActionMain && isCategoryLauncher;
}
The simplest approach that I can think of would be to pass a flag while launching the activity from your own activities. You should also check if the activity was created or resumed, this can be done by setting a boolean in the onCreate method, and then checking it onResume.
Below is the code you can use (not tested):
Activity in which you want to check (say MainActivity.class):
Boolean onCreateCalled = false;
Boolean calledFromAppActivities = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onCreateCalled = true;
Bundle mainData = getIntent().getExtras();
if (mainData != null) {
if (getIntent().hasExtra("call_from_own_activity")) {
calledFromAppActivities = true;
}
}
.....
}
#Override
protected void onResume() {
super.onResume();
if (onCreateCalled && !calledFromAppActivities) {
// The app was not called from any of our activities.
// The activity was not resumed but was created.
// Do Stuff
}
// To stop it from running again when activity is resumed.
onCreateCalled = false;
....
}
When calling MainActivity from other activities, use the code below:
private void call_main () {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("call_from_own_activity", true);
startActivity(i);
}