Aniket Bhattacharyea Aniket Bhattacharyea - 3 months ago 9
Android Question

Passing data from fragment to activity without affecting the fragment

I have one fragment in which I'm generating an

ArrayList
. After the
ArrayList
is generated, I'm sending it to the
Activity
using interface

Inside my fragment-

public interface sendTheArraylist{
void ArrayList(ArrayList<Song> songArrayList);
}


And in the MainActivity-

@Override
public void accessArrayList(ArrayList<Song> songArrayList) {
this.queueArrayList=songArrayList;

queueAdapter =new SongAdapter(this,queueArrayList);
....
}


However, I see that whenever any changes are made in the
queueArrayList
in
MainActivity
, the
songArrayList
in the fragment is also getting affected. How can I stop the
ArrayList
in the
Fragment
from getting changed?

Answer

Try with the following.

this.queueArrayList.clear();
this.queueArrayList.addAll(songArrayList);

The reason is that you are referencing the arraylist to queueArrayList directly which also reflects changes back in songArrayList

Comments