I'm passing an ArrayList of movie objects from MainActivity
to a DetailActivity
via an intent.
intent.putExtra(KEY_mFavoriteMovies, mFavoriteMovies);
startActivity(intent);
In this other activity, I'm adding additional movie objects.
mFavoriteMovies(movie);
However, mFavoriteMovies
in MainActivity
does not appear to contain the additional movie objects.
Is this behavior expected?
That is the expected behaviour because when you modify your array list at DetailActivity
you are working with a different instance of your movies list.
You can get the changes you make to the list by starting DetailActivity
with startActivityForResult
and then sending back the updated list to your MainActivity
You would have something like this at your MainActivity
ArrayList<String> mMovies;
int DETAIL_REQUEST_CODE = 123;
String KEY_FAVORITE_MOVIES = "key-movies";
private void startDetailActivity() {
Intent intent = new Intent(this, DetailActivity.class);
intent.putStringArrayListExtra(KEY_FAVORITE_MOVIES, mMovies);
startActivityForResult(intent, DETAIL_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DETAIL_REQUEST_CODE && resultCode == RESULT_OK) {
mMovies = data.getStringArrayListExtra(KEY_FAVORITE_MOVIES);
}
}
And you will have to send the updated list from the DetailActivity
with something like this:
public void finishDetail() {
Intent resultIntent = new Intent();
resultIntent.putStringArrayListExtra(KEY_FAVORITE_MOVIES, mMovies);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}