Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to retrieve intent's extras

Tags:

android

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.

like image 888
parser_failed Avatar asked Feb 04 '11 13:02

parser_failed


3 Answers

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);    
}
like image 163
Vikas Patidar Avatar answered Oct 20 '22 21:10

Vikas Patidar


Aha! I just debugged this problem. It turns out to be due to a subtle detail documented in PendingIntent.

  • A PendingIntent is a reference to a system-maintained token. So even if the sending process restarts, reconstructing a similar intent will retrieve the original PendingIntent. Then the sender can cancel or change it.
  • Similar intent == same operation, action, data, categories, components, and flags. Extras don't count!
  • Intents that differ only in their Extras all retrieve the same token.

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.

like image 44
Jerry101 Avatar answered Oct 20 '22 20:10

Jerry101


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);
like image 2
Robby Pond Avatar answered Oct 20 '22 22:10

Robby Pond