Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android intent extra data is lost

I'm trying to get some data passed along inside my app using intents' extras.

I attach data to the intent like so:

Intent i = new Intent(ActivityFrom.this, ActivityTo.class);
i.putExtra(CONST_KEY, true);
startActivity(i);

With

public static final String CONST_KEY = "MyBooleanValue";

I'm attempting to retrieve the data in the started ActivityTo's onCreate method like so:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extra = getIntent().getExtras();
    if ( extra != null ) {
        boolean b = extra.getBoolean(ActivityFrom.CONST_KEY);
    }
}

However, I never run into the if-block, because the Bundle is always null.

Why are my extras lost? What do I need to change to retrieve the extras I put to the intent?

Edit

  • Corrected the typo in code
  • Added the complete onCreate method declaration
  • Here is the ActivityTo's declaration in the manifest:

    <activity
        android:name=".ActivityTo"
        android:launchMode="singleTask"
        android:screenOrientation="portrait">
    </activity>
    
like image 235
inedible Avatar asked Nov 30 '15 08:11

inedible


1 Answers

The problem is the android:launchMode="singleTask"attribute of the receiving task. With this being set, all intents that target the ActivityTo activity are received by the same object. In case the activity was already created, the intent is sent through the activity's onNewIntent(Intent) method. Override it like this:

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

This way, you can get the new intent with the getIntent().

like image 81
inedible Avatar answered Nov 03 '22 14:11

inedible