0

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?

  • http://stackoverflow.com/questions/9343241/passing-data-between-a-fragment-and-its-container-activity/9346844#9346844 –  Aug 31 '16 at 05:19

3 Answers3

1

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

Ashik Vetrivelu
  • 1,021
  • 1
  • 9
  • 24
0

Using an interface you pass the reference of that list so whenever you change that list will also affect on fragment list too. so the solution is rather than pass a reference to that list create one new list and make copy of it.

You can try and give a look at the Collections.copy method:

public static void copy(List dest, List src)

Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. This method runs in linear time.

Parameters: dest - The destination list. src - The source list.

hope it will help you.

Himeshgiri gosvami
  • 2,559
  • 4
  • 16
  • 28
0

Here is the complete solution: before calling sendTheArraylist Inside your fragment-

ArrayList<Song> songArrayListToPass= new ArrayList<Song>(songArrayList.size());
Collections.copy(songArrayListToPass, songArrayList);
 YourActivityRef.sendTheArraylist(songArrayListToPass);

This way your any update on your songArrayListToPass inside Activity will not reflect in Fragment.

Rajendra
  • 484
  • 4
  • 19