简体   繁体   中英

Not ablet to pass Parcelable object as putExtra from IntentService to another Activity

Reivewed all the similar question, and yet no result. I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project. Code is given below(Dont have right to publish whole code,and whole code is working except these lines) CODE: IntentService:

    Intent action = new Intent(this, QuizActivity.class);
    intent.putParcelableArrayListExtra("userList",name);
    Random position = new Random();
    int randomPosition =position.nextInt(3);
    intent.putExtra("selectedUser",name.get(randomPosition));
    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

SecondActivity:

List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");

I suposse that problem can be with putting a custom Parcelable on API 25+ from service to activity.

This answer has a workaround, in the form of converting the Parcelable yourself to/from a byte[].

Begin with passing single Parcelable object, not ArrayList.

    public static void putExtra(Intent intent, String key, Parcelable parcelable) {
    byte[] bytes = marshall(parcelable);
    intent.putExtra(key, bytes);
}

and

    public static <T> T getExtra(Intent intent, String key, Parcelable.Creator<T> creator) {
    byte[] bytes = intent.getByteArrayExtra(key);
    return ParcelableUtils.unmarshall(bytes, creator);
}

Try below and when you get getParcelableArrayListExtra use same name.you have to implement User class with Parcelable.

Intent action = new Intent(this, QuizActivity.class);
intent.putParcelableArrayListExtra("userList",name);
Random position = new Random();
int randomPosition =position.nextInt(3);
intent.putExtra("selectedUser",name.get(randomPosition));
action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

In SecondActivity :

ArrayList<User> userList = getIntent().getParcelableArrayListExtra("userList");
for(User user : post){
    Log.d("user", user.getString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM