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()));
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()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With