【发布时间】:2016-08-10 05:13:16
【问题描述】:
我有一个使用游标运行 SQlite 查询的应用程序。
public Cursor totaltrips(){
Cursor cursor = database.rawQuery("SELECT * AS TTotal FROM " + DatabaseHelper.TABLE_NAME, null);
return cursor;
}
结果存储到一个最多包含 5 个值的 Arraylist 中。如果数据库中没有记录,则应用程序崩溃。如果我有一个或多个数据库条目,它工作正常。有谁知道当没有数据库条目时如何阻止它崩溃?
// 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");
}
应用程序因错误而崩溃
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
上线
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
【问题讨论】:
-
在此之前你可以检查 cursor.getCount() > 0 ...
-
只需将您的 do while 循环添加到 if/else 语句
if(curser.getCount()>0){ //do-while loop here} -
在循环之前检查 cursor.getCount() > 0
标签: android sqlite arraylist android-sqlite