Sammie Sammie - 1 year ago 77
Android Question

How to populate an ArrayList<ArrayList<String>> that contains another ArrayList<String>

I was trying to populate an arraylist to contain another arraylist but after the loop finishes adding the sub arraylist to the parent in the first round, in the next round it overwrites the previously added row and duplicates the value of 2nd round and so on; so finally i get an arraylist having duplicate rows all of them having values the last row in the cursor. To clarify it well... instead of returning something like this

[Quote1, Location1]
[Quote2, Location2]
[Quote3, Location3]
[Quote4, Location4]

it returns something like

[Quote4, Location4]
[Quote4, Location4]
[Quote4, Location4]
[Quote4, Location4]

Here is my code:

public ArrayList<ArrayList<String>> getAllVerses() {
ArrayList<ArrayList<String>> allVersesAL = new ArrayList<ArrayList<String>>();
ArrayList<String> subAL = new ArrayList<>();
Cursor allVerse = getAllQuote(); //It's an outsider method
do {
Log.d("Content of subAL", subAL + "");
} while (allVerse.moveToNext());

for (List<String> li : allVersesAL) {
for (String s : li) {
Log.d("getAllVerses", "Inside the second for loop...");
Log.d("Testing arraylist...", s + " : ");
return allVersesAL;

It assigns the data to the sub ArrayList from a cursor object. Please help!!! I spent a lot of time on this but couldn't figure out what's wrong with my code. Bless you all!

Answer Source

When you insert a object in a List the actual object is inserted into the list. It isn't copied. If you do further operations on the same object it will affect the object stored in the list.

What you need to do is to create a new ArrayList object for each iteration of the outer loop of your population code.

do {
    subAl = new ArrayList<String>();