Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Invalid SQLite Queries in Android

Tags:

android

sqlite

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;

}
like image 636
Razgriz Avatar asked Sep 14 '26 08:09

Razgriz


1 Answers

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
}
like image 143
Himanshu Mohta Avatar answered Sep 15 '26 21:09

Himanshu Mohta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!