将ArrayList <object>传递回主Activity(Android)

时间:2016-10-18 02:13:20

标签: java android arraylist onactivityresult

我有一个ArrayList&lt;对象&gt;其中Object是我所创建的类的实例。我想将这个新的数组列表传递回主活动,将其放入导航条项目中。

如何传递ArrayList&lt;对象&gt;从活动回到主要活动?

我已经尝试过bundle.getParcelableArrayList但它告诉我“类型参数T的推断类型对象不在其范围内,应该实现android.os.parcelable”

这是我的代码:

public void createPlaylist(String playlistName, ArrayList<Song> newPlaylistSongsArray) {
    Intent returnIntent = new Intent();
    Bundle b = new Bundle();
    b.putParcelableArrayList("array", (ArrayList<? extends Parcelable>) newPlaylistSongsArray);
    returnIntent.putExtra("playListName", playlistName);
    returnIntent.putExtra("array", newPlaylistSongsArray);
    setResult(Activity.RESULT_OK,returnIntent);
    finish();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK){
            String newPlaylistName = data.getStringExtra("playListName");
            Bundle b = getIntent().getExtras();
            final ArrayList<Song> newPlaylist = b.getParcelableArrayList("array");
            Toast.makeText(MP3Player.this, "New Playlist Created", Toast.LENGTH_LONG).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(MP3Player.this, "Shit went wrong yo!", Toast.LENGTH_LONG).show();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

最简单的方法是,您的Song类需要实现Serializable。

Bundle bundle = new Bundle();
bundle.putSerializable("newPlaylist", newPlaylist);
intent.putExtras(bundle);

在其他活动中:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();

ArrayList<Song> newPlaylist=
               (ArrayList<Song>)bundle.getSerializable("newPlaylist");