简体   繁体   中英

Passing ArrayList<Object> back to main Activity (Android)

I have an ArrayList< Object> where the Object is an instance of a class I made. I want to pass this new array list back to the main activity to put it in a navigationdrawer item.

How do I pass an ArrayList< Object> from an activity back to the main one?

I have tried the bundle.getParcelableArrayList however it tells me that "Inferred type Object for type parameter T is not within its bounds, should implement android.os.parcelable"

Here is my Code:

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

And:

@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();
        }
    }
}

For the easiest way, your Song class need implement Serializable.

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

in other activity:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM