Дима Родионов Дима Родионов - 5 months ago 10
Android Question

Does x=y makes x pointer to y?

I am sorry for such a stupid question, but I cant describe my problem any better. I have 2 classes:

//First Class
public class VKtracks extends Fragment {

RecyclerView list;
SongListAdapter listAdapter;
private ArrayList<song> songs = new ArrayList<>();
MainActivity mainActivity;

public VKtracks(){

}

@Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
mainActivity = (MainActivity)getActivity();
songs = mainActivity.songs;
Iterator<song> itr = songs.iterator();
while (itr.hasNext()) {
song element = itr.next();
if(element.getSource() == 0){
itr.remove();
}
}
}

//Second class

public class Tracks extends Fragment {


RecyclerView list;
private MediaPlayer mp = new MediaPlayer();
SongListAdapter listAdapter;
private ArrayList<song> songs = new ArrayList<>();
ImageButton playButton;
boolean playerActive = false;
MainActivity mainActivity;
int mLastFirstVisibleItem = 0;


public Tracks() {
}

@Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
mainActivity = (MainActivity)getActivity();
songs = mainActivity.songs;
listAdapter = new SongListAdapter(getContext(),songs, mainActivity);
listAdapter.notifyDataSetChanged();
list.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
list.setLayoutManager(llm);
list.setAdapter(listAdapter);
}
}


In both classes I am getting a list of songs from MainActivity. In the Tracks class I am just filling the RecyclerView with it, and in the VKtracks I am deliting unnecessary items with iterator and filling another RecyclerView. At the end i have 2 similar filtred lists. If I comment filtering part in the VKTracks class I am getting 2 similar unfiltred lists.

So, why this happens?

The only reasong I can suppose is that both songs ArrayLists are poiners to a songs ArrayList in the MainActivity.

Answer

Your reasoning is correct. The pointers Tracks.songs, VKTracks.songs, and MainActivity.songs are all point to the same list, so modifying either will change all three. Try using the ArrayList copy constructor in Tracks and VXTracks to create three unique array lists. To do this, replace the line

songs = mainActivity.songs;

with

songs = new ArrayList(mainActivity.songs);

in both Tracks and VKTracks.

Comments