squidpickles squidpickles - 13 days ago 5
Android Question

Intent extras remain the same even when updated

I am trying to pass a small bit of text between

Activity
instances using an
Intent
with extras.

This seems to work fine whenever I navigate between them using the back button or navigation in the action bar. However, if I visit the home screen and then relaunch the application, the extras passed are ignored; the second
Activity
seems to use the old
Intent
, rather than the new one.

The relevant code:

Source activity

public class ActivityA extends Activity {
protected void goToResults(String results) {
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(Intent.EXTRA_TEXT, results);
startActivity(intent);
}
}


Destination activity

public class ActivityB extends Activity {
@Override
public void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
String results = extras.getString(Intent.EXTRA_TEXT);
// etc
}
}


I have tried a number of different things, including:

intent.setAction("action-" + UNIQUE_ID);


(as I understand that
Intent
instances are not compared by content of extras)

PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


(I don't need
PendingIntent
, but thought this might force the
Intent
to update)

Any suggestions for how to force the
Intent
to show the changed data every time I make the transition from
ActivityA
->
ActivityB
, regardless of whether I'm using the back button or a diversion to the home screen?

Answer

I remember running into this issue once, we solved it by either adding Intent.FLAG_ACTIVITY_CLEAR_TOP to the intent you are sending:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

or by implementing the following method into the activity you're intent is launching:

protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
}

I'm not 100% sure what fixed it again, believe it was adding the onNewIntent method. Good luck and let us know.