Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App crashes if SQLite cursor has no results

I have an app that uses a cursor to run an SQlite query.

    public Cursor totaltrips(){
    Cursor cursor = database.rawQuery("SELECT * AS TTotal FROM " + DatabaseHelper.TABLE_NAME, null);
    return cursor;
}

The results are stored to an Arraylist with a maximum of 5 values. If there are no records in the database the app crashes. If I have one or more database entries it works fine. Does anyone know how I can stop it from crashing when there are no database entries?

 // get column value
    if (Distance.moveToNext())
        result = String.valueOf(Distance.getDouble(Distance.getColumnIndex("myTotal")));

    tnmView.setText(result);

    List<String> distancearray = new ArrayList<String>();
    Cursor cursor =  dbManager.totaldistance();


    do{
        distancearray.add(cursor.getString(1));
    }while ((cursor.moveToNext()));
    ttrips = cursor.getCount();
    Log.i("Graph", "TTRIPS = " + ttrips);

    // Be sure here to have at least the 5 desired elements into the list
    while(distancearray.size() < 5){
        distancearray.add("0");
    }

The app crashes with the error

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

On the line

do{
        distancearray.add(cursor.getString(1));
    }while ((cursor.moveToNext()));
like image 514
MarcusRey Avatar asked Apr 18 '16 12:04

MarcusRey


1 Answers

Check if cursor actually has results, try something like this for example:

int numResults = cursor.getCount();
if (numResults > 0) {
    do {
        distancearray.add(cursor.getString(1));
    } while ((cursor.moveToNext()));
}
like image 125
Slobodan Antonijević Avatar answered Sep 23 '22 18:09

Slobodan Antonijević