2017-07-09 86 views
0

找回所有类似的问题,但没有结果。 我无法将一个从intentService实现parcelable的ojbect传递给一个Activity。将数据从活动传递到另一活动时,相同的代码正常工作。即使可以传递ParcelableArrayListExtra也不可以传递对象。它是在我的项目中传递对象的一个​​要求。下面 代码给出(不要有权发布完整的代码,并且整个代码工作,除了这些线路) CODE: IntentService:不能将作为putExtra的Parcelable对象从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"); 
+0

请解释**详细**什么 “我无法通过一个ojbect实现parcelable从intentService到活动” 是指什么“但不是可以parcelable的对象”的意思。你的症状是什么? – CommonsWare

+0

你收到异常吗? – Alex

+0

您的测试设备使用哪个api级别? – mac229

回答

0

我suposse那问题可能是将服务和活动之间的自定义Parcelable放在API 25+上。

这个answer有一个解决方法,以Parcelable自己转换为byte []的形式。

从传递单个Parcelable对象开始,而不是ArrayList。

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

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

不允许这样做... –

0

下面尝试,当你得到getParcelableArrayListExtra使用相同的name.you必须实现与Parcelable User类。

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); 

在SecondActivity:

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