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
allVerse.moveToFirst();
do {
//subAL.clear();
subAL.add(allVerse.getString(allVerse.getColumnIndex(VERSE)));
subAL.add(allVerse.getString(allVerse.getColumnIndex(LOC_AUTH)));
Log.d("Content of subAL", subAL + "");
allVersesAL.add(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!
subAlto your enclosing listallVersesAL. Instead of that, make a new inner list each time.//subAL.clear();will probably solved your problemsubAlhas been added toallVersesAL, there is no harm in clearing it and again add new values. It's same like create new instance ofsubAlsubAlafter adding it, you will clear the list that has been inserted (because it is the same object!).