我有一个使用游标运行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()));
答案 0 :(得分:7)
检查光标是否确实有结果,尝试类似这样的事情:
int numResults = cursor.getCount();
if (numResults > 0) {
do {
distancearray.add(cursor.getString(1));
} while ((cursor.moveToNext()));
}
答案 1 :(得分:1)
替换
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
与
if (cursor != null) {
while (cursor.moveToNext()) {
distancearray.add(cursor.getString(1));
}
cursor.close();
}
答案 2 :(得分:1)
检查游标是否为空且具有多个值。使用后关闭游标。
public MainWindow() {
xpsViewer.AddHandler(Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(OnRequestNavigate));
}
private void OnRequestNavigate(object sender, RequestNavigateEventArgs e) {
// URI contains the page number (e.Uri = "...#PG_7_LNK_2")
int pageNumber;
if (int.TryParse(Regex.Match(e.Uri.ToString(), @"(?<=PG_)[0-9]+").Value, out pageNumber)) {
xpsViewer.GoToPage(pageNumber);
}
}