2017-07-09 87 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()); 
} 
相關問題