[英]How to pass an ArrayList and an integer to a new activity (Android)
給意圖一個歌曲的ArrayList后,我就無法啟動新活動,我的代碼在這里:
ArrayList<Song> songs = new ArrayList<>();
songs.add(new Song("title", "artist"));
Intent intent = new Intent(this, Game.class);
int dif = 0;
Bundle bundle = new Bundle();
if (songs != null) {
bundle.putParcelableArrayList("DEVICE_SONGS", songs);
bundle.putInt("DIFFICULTY", dif);
intent.putExtras(bundle);
}
startActivity(intent);
Song已經實現了Parcelable。
當startActivity
運行時, Game
活動不會啟動,而是轉到父活動,日志中沒有錯誤。
我嘗試了此操作,但未將bundle
添加到intent
,並且正確的活動開始了。
感謝您的任何幫助,謝謝
編輯
我現在嘗試使用putParcelableArrayListExtra()
如下:
if (songs != null) {
intent.putParcelableArrayListExtra("DEVICE_SONGS", songs);
intent.putExtra("DIFFICULTY", dif);
}
和我有同樣的問題。 我也不嘗試訪問有關新活動的其他內容。
編輯2
經過一些測試(在虛擬設備上),它實際上可以工作,所以我認為這與我使用的設備(帶有Oxygen OS的Oneplus X)有關。 所以現在的問題是,如何使它在所有設備上都能正常工作?
/**
* Add extended data to the intent. The name must include a package
* prefix, for example the app com.android.contacts would use names
* like "com.android.contacts.ShowAll".
*
* @param name The name of the extra data, with package prefix.
* @param value The ArrayList<Parcelable> data value.
*
* @return Returns the same Intent object, for chaining multiple calls
* into a single statement.
*
* @see #putExtras
* @see #removeExtra
* @see #getParcelableArrayListExtra(String)
*/
public Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putParcelableArrayList(name, value);
return this;
}
軟件包名稱前綴!
首先,您的Song類必須實現Parcelable,鍵入以下內容:
public class MyClass implements Parcelable {
public final int num1;
public final int num2;
public MyClass(final int num1, final int num2) {
this.num1 = num1;
this.num2 = num2;
}
public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
public MyClass createFromParcel(Parcel in) {
return new MyClass(in);
}
public MyClass[] newArray(int size) {
return new MyClass[size];
}
};
public vonum1 writeToParcel(Parcel dest, int flags) {
dest.writeInt(num1);
dest.writeInt(num2);
}
private MyClass(Parcel in) {
num1 = in.readInt();
num2 = in.readInt();
}
}
現在,您可以使用bundle.putParcelableArrayListExtra將列表傳遞給另一個活動。
要通過ArrayList:
ArrayList<Song> songs = new ArrayList<>();
songs.add(new Song("title", "artist"));
Intent intent = new Intent(this, Game.class);
bundle = new Bundle();
bundle.putParcelableArrayList("song", songs);
intent.putExtras(bundle);
用於檢索ArrayList
ArrayList<Song> songs;
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey("song")){
songs = bundle.getParcelableArrayList("songs");
}
您可以嘗試發送一個Parcelable Array而不是ArrayList
ArrayList<Parcelable> a =new ArrayList<Parcelable>();
Parcelable[] b = new Parcelable[a.size()];
a.toArray(b);
i.putExtra("YOUR_DATA_LIST",b);
Intent
可以傳遞的數據量是有限制的,此處超出了限制。 如果我限制songs
的大小,那沒問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.