I have an application 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 saved in Arraylist with a maximum value of 5. If there are no entries in the database, the application 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 records in the database?
// 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 application crashes with an error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
In line
do{ distancearray.add(cursor.getString(1)); }while ((cursor.moveToNext()));
source share