Search code examples
javaandroidsqlitearraylistandroid-sqlite

How to loop through a cursor in SQLite once, close and move to next without displaying the first row again


I'm trying to loop through an arrayList but the problem is everytime it loops, first loop it is showing only one element, second loop it is showing the previous one and a new one and the cycle continues, I want to only show one element at a time, here's how I'm doing it:

private void checkDB() {
    Cursor data = mDatabaseHelper.getData();
    ArrayList<String> list1 = new ArrayList<String>();
    ArrayList<String> list2 = new ArrayList<String>();
    ArrayList<String> list3 = new ArrayList<String>();
    ArrayList<String> list4 = new ArrayList<String>();

    if (data.getCount() == 0) {
        Toast.makeText(context, "No Data", Toast.LENGTH_SHORT).show();
    }
    while (data.moveToNext()) {
        list1.add(data.getString(1));
        list1.add(data.getString(2));
        list1.add(data.getString(3));
        list1.add(data.getString(4));
        Log.e(TAG, "checkDB1: " + list1);
    }
}

And this is the result:

checkDB1: [3586, 4801, 02305767706, testeOM004]
checkDB1: [3586, 4801, 02305767706, testeOM004, 3586, 4801, 02305767671, testeOM001]
checkDB1: [3586, 4801, 02305767706, testeOM004, 3586, 4801, 02305767671, testeOM001, 3586, 4801, 02305767682, testeOM002]
checkDB1: [3586, 4801, 02305767706, testeOM004, 3586, 4801, 02305767671, testeOM001, 3586, 4801, 02305767682, testeOM002, 3586, 4801, 02305767693, testeOM003]

Everytime it loops, it shows the previous one too, I'm trying to print only one data and not previous one, I've tried few solution from stack but still the same. Other that I've tried:

for (data.moveToNext(); data.isAfterLast(); data.moveToNext()) {
    list1.add(data.getString(1));
    list1.add(data.getString(2));
    list1.add(data.getString(3));
    list1.add(data.getString(4));
    Log.e(TAG, "checkDB1: " + list1);
}

Solution

  • All you have to do is clear the list at the end of each iteration of the while loop:

    while (data.moveToNext()) {
        list1.add(data.getString(1));
        list1.add(data.getString(2));
        list1.add(data.getString(3));
        list1.add(data.getString(4));
        Log.e(TAG, "checkDB1: "+list1);
        list1.clear();
    }