Search code examples
javaandroidarraylistparceler

Android ArrayList of String objects size remains at 0 despite adding to it


I have created a custom class called Song which contains 3 String variables, an int variable and an ArrayList of String items.

Now I have the correct getters and setters for all of the variables and such, however the issue is that, when I assign something to the ArrayList variable and try to access it later, it throws an IndexOutOfBounds error because the size of it is 0. Below is the code in question.

Is it possible that I'm not assigning the variable correctly or possibly its memory location is being affected by clearing it?

Important note: I am able to access and print the values of the other variables but the ArrayList variable is the only one that fails.


SongClass.java

@Parcel
public class SongClass {
    //Other variables defined here
    ArrayList <String> verses;

    public Song() { /*Required empty bean constructor*/ }

    public Song(String var1, String var2, String var3, int var4, ArrayList<String> verses) 
    {
        this.var1= var1;
        this.var2= var2;
        this.var3= var3;
        this.var4= var4;
        this.verses = verses;
    }

    //Getters and Setters below

SongReader.java

//Use to store a collection of Song objects (multiple songs)
private ArrayList<Song> songs = new ArrayList<>(10);

//This array will be assigned to the Song object -> verses
private ArrayList<String> verses = new ArrayList<>(10); 
//Other vars to be assigned to song object (String, String, String, int)

...

songs.add(new Song(String var1, String var2, String var3, int var4, verses);

//Important note: I clear the verses `ArrayList` after assigning it to songs. Could this possibly erase it from songs?
verses.clear();

SongDisplay.java

ArrayList<Songs> songs = Parcels.unwrap(intent.getParcelableExtra("Extras"));

...

for (int i = 1; i <= songs.get(0).size(); ++i)
{
    TextView textView = new TextView(this);
    ...
    //Error is thrown here
    textView.setText(songs.get(0).getVerses().get(i-1);
    ...
 }

Solution

  • Your comment is correct. Since the ArrayList you pass to song and the ArrayList you call clear() on are the same object they both get cleared.

    If you need to clear the ArrayList pass a new ArrayList into the Song constructor that copies the contents of verses.

    songs.add(new Song(String var1, String var2, String var3, int var4, new ArrayList(verses));
    

    Also, note that arrays and lists in java start at index 0 so you should fix the for loop too.

    // hard coding songs.get(0) could lead to issues as well but at least fix the index i
    for (int i = 0; i < songs.get(0).size(); i++)
    {
        TextView textView = new TextView(this);
        ...
        //Error is thrown here
        textView.setText(songs.get(0).getVerses().get(i);
        ...
     }