3

I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.

My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.

So far my method for searching looks like this:

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 に答える