lundi 18 avril 2016

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()));

Aucun commentaire:

Enregistrer un commentaire