I have a problem with the application I’m trying to develop.
It’s a music game for Android, I obtain all the data from iTunes.
This is the part where i get the data. I have 2 lists:
- List canzoni: size 5, fields: previewUrl, artistName, trackName, artistViewUrl and artworkUrl100.
- List dieciCanzoni: size 10, must contain 10 elements of the above list.
This is the code that fills the lists:
try
{
int randomLookupId;
JSONObject obj = getJSONObject(url);
JSONArray jsonArray = obj.getJSONArray("resultIds");
for(int i = 0; i < 10; i++)
{
canzoni.clear();
randomLookupId = new Random().nextInt(jsonArray.length());
JSONObject finalObj = getJSONObject("http://itunes.apple.com/lookup?id="+jsonArray.getString(randomLookupId));
JSONArray finalJsonArray = finalObj.getJSONArray("results");
JSONObject returnObj = finalJsonArray.getJSONObject(0);
canzoni.add(returnObj.getString("previewUrl"));
canzoni.add(returnObj.getString("artistName"));
canzoni.add(returnObj.getString("trackName"));
canzoni.add(returnObj.getString("artistViewUrl"));
canzoni.add(returnObj.getString("artworkUrl100"));
Canzone.dieciCanzoni.add(i, canzoni);
}
}
catch (JSONException ignored)
{
ignored.getCause();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
The retrieval of informations works very well, I have only one problem: when I clear the list canzoni, I noticed that the list dieciCanzoni has been cleared too, and obviously I don’t want that!
And if I comment the line that clear the canzoni list, in the dieciCanzoni list is inserted only the last values in canzoni, even the previously inserted values change!
Can you help me please figuring it out?
Thank you all!
You need to use a deep copy:
or:
What’s happening is
Canzone.dieciCanzoni.add(i, canzoni);only points to the same location where the information is stored. When you clear either list you are clearing the one location for both of them. A “deep copy” duplicates the data so each list has it’s own copy.Better yet, don’t use
clear(). Simply create a new list forcanzonifrom the start. Replace:with: