![](/img/trans.png)
[英]Android Studio, Passing 1 ArrayList between 2 Activites
[英]Passing ArrayList<Object> in Android Studio w/ Lastfm API
我正在嘗試將相冊類型的ArrayList傳遞給Android Studio中的另一個活動。
問題是我正在使用的Lastfm API無法實現Parcelable。
我嘗試制作自己的專輯類並擴展他們的專輯類,但出現錯誤
“'de.umass.lastfm.Album'中沒有默認的構造函數
Quiz.java-intent.getParcel ...不起作用,因為專輯不可包裹
public class Quiz extends AppCompatActivity {
private static TextView tv_quiz;
private static EditText et_quiz;
private ArrayList<Album> albums;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent = getIntent();
albums = intent.getParcelableArrayListExtra(MainActivity.ALBUMS_LIST);
}
}
我的MainActivity.java的調用部分。
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(ALBUMS_LIST, allAlbums);
intent.putExtra(DIFFICULTY, difficulty);
startActivity(intent);
有什么辦法可以解決這個問題?
不管怎么說,還是要謝謝你
這是使用此代碼的解決方案開放活動
Bundle bundle = new Bundle();
bundle.putSerializable("data", allAlbums);
bundle.putString(DIFFICULTY", difficulty);
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(bundle);
startActivity(intent);
獲取意圖數據
albums = (ArrayList<Album>) getIntent().getExtras().getSerializable("data");
更新了專輯類
public class Album implements java.io.Serializable {
//your code
}
我查看了您鏈接的api,“ Album
看起來很難打包。 我想說,您最好在下一個Activity中重新加載列表(而不是嘗試傳遞列表)。
“構造”新Album
實例的唯一方法是通過getInfo()
靜態工廠方法。 您可以創建一個可拆分的新類AlbumWrapper
,通過Intent發送一個AlbumWrapper
列表,然后在另一側使用getInfo()
重新獲取相冊。
public class AlbumWrapper implements Parcelable {
// insert CREATOR here
public final String artist;
public final String mbid;
public AlbumWrapper(Album a) {
this.artist = a.getArtist();
this.mbid = a.getMbid();
}
private AlbumWrapper(Parcel in) {
this.artist = in.readString();
this.mbid = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
dest.writeString(mbid);
}
@Override
public int describeContents() {
return 0;
}
}
您可以像這樣將您的“相冊”列表放在意圖中:
ArrayList<AlbumWrapper> wrappers = new ArrayList<>();
for (Album album : albums) {
AlbumWrapper wrapper = new AlbumWrapper(album);
wrappers.add(wrapper);
}
intent.putParcelableArrayListExtra("ALBUM_WRAPPERS", wrappers);
然后在下一個活動中,您可以執行以下操作:
List<AlbumWrapper> wrappers = getIntent().getParcelableArrayListExtra("ALBUM_WRAPPERS");
List<Album> albums = new ArrayList<>();
for (AlbumWrapper wrapper : wrappers) {
Album album = Album.getInfo(wrapper.artist, wrapper.mbid, YOUR_API_KEY);
albums.add(album);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.