3

我有一个简单的代码可以成功查询 SQLite 数据库并将结果从光标转换为字符串,以便在屏幕上显示。

我现在的问题是导致应用程序崩溃的无效查询。有没有办法成功处理无效查询?最好是可以防止我的应用程序崩溃并且只会将用户重定向到主页并显示警告的东西。

到目前为止,我的搜索方法如下所示:

public String search(DataBaseHelper myDB){
    SQLiteDatabase db = myDB.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);

    cursor.moveToFirst();

    String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
                    cursor.getString(cursor.getColumnIndex("Room"));

    //Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
    //msg.show();

    cursor.close();

    return data;

}
4

2 回答 2

4
Cursor cursor = NULL ;
try
{
   cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
   if(cursor != NULL)
   {
      try {
         if (cursor.moveToNext()) {
            String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + 
               " " + cursor.getString(cursor.getColumnIndex("Room"));
         } else {
            // Query result was empty, deal with it here.
         }
      } finally {
        // Cursors should be closed
        cursor.close();
      }
   }
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
    //print exception
}
于 2012-06-04T07:28:10.583 回答
1
Cursor cursor = null;
String data = "";
try 
{
    cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
    // TODO: handle exception
}
于 2012-06-04T07:29:53.007 回答