Application crashes if SQLite cursor has no results

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())); 
+5
source share
3 answers

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

 int numResults = cursor.getCount(); if (numResults > 0) { do { distancearray.add(cursor.getString(1)); } while ((cursor.moveToNext())); } 
+7
source

Replace

 do{ distancearray.add(cursor.getString(1)); }while ((cursor.moveToNext())); 

with

 if (cursor != null) { while (cursor.moveToNext()) { distancearray.add(cursor.getString(1)); } cursor.close(); } 
+1
source

Check if the cursor is null and has more than one value. Close the cursor after use.

 if(cursor!=null&&cursor.getCount()>0){ cursor.moveToFirst(); while(cursor.hasNext()){ //do stuff here } cursor.close(); } 
+1
source

Source: https://habr.com/ru/post/1247361/


All Articles