Reputation: 697
I have an activity that I use in multiples modes, so I have to do things like this:
Intent i = new Intent(MainListActivity.this,MainActivity.class);
extras.putInt("id", c.getId());
extras.putInt("mode", AREA_MODE);
i.putExtra("extras", extras);
startActivity(i);
and in the onCreate
:
Intent i = this.getIntent();
extras = i.getBundleExtra("extras");
if(extras!=null){
id = extras.getInt("id", -1);
mode = extras.getInt("mode", COUNTRY_MODE);
}
But the intent extras are always null. Am I missing something? Is there any way to do this?
EDIT: For some reason, the getIntent()
method returns the previous Intent
which in my case has no extra (main intent). I'm trying to figure out why.
Upvotes: 5
Views: 6131
Reputation: 13447
Aha! I just debugged this problem. It turns out to be due to a subtle detail documented in PendingIntent.
A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen.
Fix 1: Make a distinct PendingIntent. It must have different operation, action, data, categories, components, or flags -- or request code integers.
Fix 2: Use FLAG_CANCEL_CURRENT
or FLAG_UPDATE_CURRENT
to cancel or modify any existing PendingIntent.
Those two fixes produce slightly different results. Either way, your new Extras should get through.
Upvotes: 4
Reputation: 697
I didn't find the cause of this issue so i gave up on using one activity. I have create others activities extending the problematic one and it started working (with both approach). Thank you all for your help.
Upvotes: 0
Reputation: 73494
It should be this.
Intent i = new Intent(MainListActivity.this ,MainActivity.class);
i.putExtra("id", c.getId());
i.putExtra("mode", AREA_MODE);
startActivity(i);
and
Intent i = this.getIntent();
id = i.getIntExtra("id", -1);
mode = i.getIntExtra("mode", COUNTRY_MODE);
Upvotes: 2
Reputation: 87593
You do not add extras to an intent this way:
i.putExtra("extras", extras);
This puts an extra called "extras" into the intent. Your "extras" are in a non-standard place in the intent. If your onCreate()
code were to retrieve the object mapped to "extras" and look in it, you would find your "extras".
The standard way is to populate a bundle and add it to the intent via putExtras:
i.putExtras(bundle);
or use the convenience methods like putExtra:
i.putExtra("mode", AREA_MODE);
Upvotes: 0
Reputation: 43359
Try like this:
In one Activity:
Intent i = new Intent();
Bundle bundle = new Bundle();
bundle.putInt("id", c.getId());
bundle.putInt("mode", AREA_MODE);
i.putExtras(bundle);
In Another Activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getInt("id", -1);
mode = extras.getInt("mode", COUNTRY_MODE);
}
Upvotes: 3