inedible
inedible

Reputation: 382

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

Upvotes: 9

Views: 5738

Answers (3)

Raed
Raed

Reputation: 904

Please make sure that your object properties in writeToParcel(Parcel parcel, int flags) match reading from parcel in YourObject(in)

for example

public class User implements Parcelabel { 
private String name;
private String addrss;
private String city;

// read from parcel
protected User(Parcel in) {
name = parcel.readString();
address = parcel.readString();
city = parcel.readString();
}

// write to parcel
writeToParcel(Parcel parcel, int flags){
parcel.writeString(name);
parcel.writeString(address);
parcel.writeString(city);
}
}

Upvotes: 0

inedible
inedible

Reputation: 382

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().

Upvotes: 13

Prakhar
Prakhar

Reputation: 710

I think you should try

if(getIntent().getBooleanExtra(ActivityFrom.CONST_KEY,false)!=null){
     Boolean b=getIntent().getBooleanExtra(ActivityFrom.CONST_KEY,false);
}

Upvotes: -3

Related Questions