I would like to pass data between activities. When I use one activity (Details), everything works fine, but when I add a second activity (MapsActivity), the application ignores (Details) and transfers data only to MapsActivity. How can I fix it? Thanks in advance
holder.itemView.setOnClickListener(v -> {
Intent mIntent = new Intent(context, Details.class);
Intent mapIntent= new Intent(context,MapsActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("Country_CurrencyCode", pozycja.getCurrencies().get(0).getCode());
mIntent.putExtra("Country_CurrencyName", pozycja.getCurrencies().get(0).getName());
mIntent.putExtra("Country_CurrencySymbol", pozycja.getCurrencies().get(0).getSymbol());
context.startActivity(mIntent);
mapIntent.putExtra("Country_Lat",pozycja.getLatlng().get(0));
mapIntent.putExtra("Country_Lng",pozycja.getLatlng().get(1));
context.startActivity(mapIntent);
This is a behavior I did not expect but after testing your code, I found these:
You start 1st the Details activity and 2nd the MapsActivity.
The result is that you see on the screen the 2nd activity: MapsActivity.
For this activity you can check that it's got all the extra values that you passed.
What is happening is that although you have also started the 1st activity: Details, its onCreate() has not yet been invoked, but it will be invoked as soon as you close the 2nd activity MapsActivity and then you will see that its extras are there as you put them. So the 1st activity gets the extras fine but until its onCreate() is called you can't access them.
So a workaround:
Start only Details activity but pass to it not only its own extras but MapsActivity's extras also. In Details's onCreate() start MapsActivity with
its own extras.
Related
I have two activities, A & B. A has a button to go to B. B sets some parameters using Seekbars.
When I go back to A there is no problem. But, I when again go to B, the Seekbars do not show the changed value.
I tried looking for solutions and I came to know about "Intent" class but the concept is not clear to me.
What is a simple clean solution to see the changed values when going to the Activity B again from Activity A?
When we want to move between activities, we use Intent. For e.g. If I have two activities ActivityA and ActivityB, I will do something like this:
Intent intent = new Intent (Activity.this, Activity.class) ;
startActivity (intent) ;
But I want to pass some values from one activity to another, Intents are also useful for that. Lets say I want to pass some string value:
In ActivityA (before starting the activity):
Intent intent = new Intent (Activity.this, Activity.class) ;
intent.putExtra("key", "value");
startActivity (intent) ;
And in ActivityB (inside onCreate) :
Intent intent = getIntent() ;
String test = intent.getString("key");
And here you have your value. You can also pass objects if you want by implementing serializable/parcelable class. Read about it:
How to pass value using Intent between Activity in android
https://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html
You should use intent.putExtra() and intent.getExtra().
You can see the example here; https://stackoverflow.com/a/14017737/8883361
Inside a broadcast receiver I want to start my app (Activity) and pass in some data.
My problem is that the extras don't seem to carry over into the activity. I am trying to get the data inside the onNewIntent(Intent i) function.
Any ideas?
Here is my current attempt in the BroadcastReceiver:
Intent intSlider = new Intent();
intSlider.setClass(UAirship.shared().getApplicationContext(), SliderMenuActivity.class);
intSlider.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intSlider.putExtra("action", ScreensEnum.Object);
intSlider.putExtra("objectId", objectId);
intSlider.putExtra("objectCode", objectCode);
intSlider.putExtra("userId", userId);
UAirship.shared().getApplicationContext().startActivity(intSlider);
EDIT - Added code used in onNewIntent() and onCreate()
The following code works great in onCreate() when the app isn't currently running. For when the app is already running the same code doesn't work (i.e. no extras) from the onNewIntent() function.
Intent intent = getIntent();
if(intent.hasExtra("objectId")) {
loadDetail(intent.getStringExtra("objectId"), "2w232");
}
The problem is getIntent() method. It always returns the intent that started the activity, not the most recent one. You should use intent that was passed to onNewIntent method as an argument.
We stumbled upon this problem once, when we were trying to launch/call onNewIntent on an Activity in response to a local notification tap. The extras that we put on our Intent were disappearing at the time onNewIntent received it.
I don't remember this being documented anywhere back then, but the "problem" was that we weren't setting the action field on the Intents that we prepared. Turns out if the Intent received by your Activity doesn't have an action set using setAction, the system still delivers the Intent to its destination, but doesn't transmit the extras you have set while creating the Intent.
TL;DR:
If you encounter this problem with an Intent with no action, calling setAction to set an arbitrary action value before sending the Intent might fix it.
Extract from the docs
This is called for activities that set launchMode to "singleTop" in
their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag
when calling startActivity(Intent). In either case, when the activity
is re-launched while at the top of the activity stack instead of a new
instance of the activity being started, onNewIntent() will be called
on the existing instance with the Intent that was used to re-launch
it.
An activity will always be paused before receiving a new intent, so
you can count on onResume() being called after this method.
Note that getIntent() still returns the original Intent. You can use
setIntent(Intent) to update it to this new Intent.
I think the last paragraph explains your problem.
You have to set the flag FLAG_ACTIVITY_SINGLE_TOP or set launchMode singleTop in the manifest file.
Of course when onNewIntent is called you do not use getIntent but the Intent received as argument.
onNewIntent will be called when the activity instance already exists. For example, if last time you pressed the Home Screen button.
I wrote a solution that worked for me here: Intent with old extra in onCreate() for singleTask Activity
You can store the last received intent in a member variable (mLastIntent).
Then you can use this member in your onResume() method to query for your extra data.
private Intent mLastIntent;
#Override
protected void onNewIntent(Intent intent) {
mLastIntent = intent;
};
In my game I am trying to pass the score from the PlayGame activity to the Scoreboard activity using an Intent Extra.
On finishing the game, I go to the scoreboard in this way:
Intent intentScoreboard = new Intent(getApplicationContext(), Scoreboard.class);
intentScoreboard.putExtra("com.example.game.SCORE", score_counter);
startActivity(intentScoreboard);
and then in the Scoreboard class I retrieve it in the onResume() method like this:
Bundle b = getIntent().getExtras();
int score = b.getInt("com.example.game.SCORE");
This works fine the first time, but if I then play another game and on finishing return to the scoreboard, I still get the score from the first game.
What am I missing?
you are missing calling setIntent()
try this:
let your score activity do a finish() if you get back to start a new game
then it should be working
getIntent delivers the intent which started the activity. If the activity is resumed you get not the most recently received intent. See here for the solution: https://stackoverflow.com/a/6838082/1127492
Bundle is not much needed to receive getExtra() values.
In my code, i have used to receive like this,
int score = getIntent().getIntExtra("com.example.game.SCORE",defaultValue);
It should works for your problem. And also it won't gives you the already received values.
Hope it sounds good for you dude.
In Android 2.3.3, how does one differentiate Intents that start a particular Activity. For example, if both Activity_A and Activity_B have intents that call startActivityForResult( intent, requestCode), how does Activity_C differentiate between which Activity has started it? Also, I know that one passes a requestCode to the starting Activity, but how does this Activity handle the requestCode? There is no method in Intent that says getRequestCode(). Is the only way to do this to place the requestCode in a Bundle in addition to the method startActivityForResult? Thanks!
Intent API:
http://developer.android.com/reference/android/content/Intent.html
One solution would be to pass along an extra piece of identifying data. For example:
intent.putExtra("activity", "com.whatever.MyActivity");
Then the receiving Activity can read it:
Bundle extras = getIntent().getExtras();
String activityName = extras.getString("activity");
It seems like there should be an easy method call to tell what the sending Intent was, but if so, I'm not aware of it.
I am intercepting sms messages with some information in them. Then in my SmsListener I'm creating notification to show in statusbar.
Then, when user clicks on a notification I want
Bring MainActivity to foreground (If such activity does not exist yet it should be created)
Pass to it data from the sms
Perform some ui changes basing on this data in this MainActivity
My activity is defined as
<activity
android:name=".MainActivity"
android:screenOrientation="sensor"
android:label="#string/app_name"
android:launchMode="singleTask"/>
Activity is launched as
Intent i = new Intent();
i.setClass(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Also in my activity I have overridden method onNewActivity
#Override
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
// I have data from broadcast in intent variable passed to this activity
processDataFromBroadcast(intent);
}
It works fine if the MainActivity already exists but if MainActivity does not exist it is started however onNewIntent was not called
Then I tried to invoke processDataFromBroadcast from onCreate: processDataFromBroadcast(getIntent()).
First time data is passed correctly from my broadcast to the activity.
However if MainActivity is sent to background and then again brought to foreground either onCreate or onNewIntent is called and processDataFromBroadcast is executed again with intent sent by broadcast and thus my MainActivity is updated with data from broadcast every-time the app is bringing to foreground - the latter is unwanted, how can I make my activity to forget this intent after first handling.
Here is sample application.
For an activity to launch only one instance of itself, have a look at the <activity> manifest element, and particularly android:launchMode. You want to configure it with either singleTask or singleInstance.
To pass data to your activity, you add data to the Intent you use to open it. To pass data with the intent, use the putExtra() methods of the intent before sending it off, and getExtra() methods to retrieve them in your receiving activity.
I'm assuming that you know roughly how intents work, but if not you could learn more about intents by taking a look at this Android developers article.
in case your problem is still unresolved, as I was just running into the same issue, here's how I solved it:
I am putting a timestamp as intentId as an extra upon the intent during it's creation. the first time, I am handling the intent in onCreate() or onNewIntent() I am reading the intentId and store it as the last intent handled. so the next time onCreate() or onNewIntet() is invoked I can check the intentId and if it equals the id of the last intent handled, I ignore it! It don't know if this helps in your case, maybe you can adopt it.
To keep intentId independent from activity lifecycles you could persist it in the userdefaults.
I agree that one would expect calling setIntent(new Intent()) in onNewIntent should do the trick.
It it late to answer, but it might be helpful to others looking for the solution.
Just add below lines of code :
Intent mIntent = new Intent(this, SplashActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // You need this if starting the activity from a service
mIntent.setAction(Intent.ACTION_MAIN);
mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Where SplashActivity is the name of initial application that is the first screen of your application.
Hope it helps. :)