Search code examples
androiddatabasesqliteloopscursor

Iterating specific count of data from a Cursor in Android


I want to iterate through a cursor data from a database, i won't be returning all of the data from the cursor. I would only need 5 randomized row of data I have the logic to return all data below but I only want five rows to be returned.

  private ArrayList<Insect> insectList(){


    ArrayList<Insect> insects = new ArrayList<>();
    Collections.shuffle(insects);

    if (cursor.moveToFirst()) {
        do {
            Insect insect = new Insect();
            insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
            insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
            insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
            insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
            insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));

            insects.add(insect);
        } while (cursor.moveToNext());
    }



    return insects;
}

Which perfect loop can i use to achieve only five rows from this cursor while iterating


Solution

  • if (cursor.getCount() > 0) {
        int count = 0;
        while (cursor.moveToNext()){
             if(count < 5){ 
                 count++;
                 Insect insect = new Insect();
            insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
            insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
            insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
            insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
            insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));
    
            insects.add(insect);
             }
        }
        cursor.close();
    }