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
onCreate
method declarationHere is the ActivityTo
's declaration in the manifest:
<activity
android:name=".ActivityTo"
android:launchMode="singleTask"
android:screenOrientation="portrait">
</activity>
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With