Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 458
squidpickles Avatar asked Oct 22 '13 23:10

squidpickles


2 Answers

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:

@Override
protected void onNewIntent(final 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.

like image 70
Lauw Avatar answered Sep 18 '22 00:09

Lauw


as @Lauw says :

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

this.setIntent(intent);

This line solved the problem for me.

like image 30
Amr Mohammed Avatar answered Sep 20 '22 00:09

Amr Mohammed