veinhorn
veinhorn

Reputation: 2403

SQLiteException when i try to check that the table is empty

When I try to check if the recent table is empty I get SQLiteException. How can i fix this trouble?

This is my sqlitehelper class:

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    private final static int DATABASE_VERSION = 1;
    private final static String DATABASE_NAME = "LyricsFinderDB";

    public MySQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        // SQL statement to create recent table
        String CREATE_RECENT_TABLE = "CREATE TABLE recent ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name INTEGER)";
        database.execSQL(CREATE_RECENT_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        database.execSQL("DROP TABLE IF EXISTS recent");
        this.onCreate(database);
    }

    public boolean isRecentTableEmpty() {
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT * FROM recent", null);

        if(cursor.getCount() > 0) {
            cursor.close();
            return false;
        }
        cursor.close();
        database.close();
        return true;
    }
}

In MainActivity I use it like in this code:

if(mySQLiteOpenHelper.isRecentTableEmpty()) {
            //...do something
        } else {
            //...do something
        }

This is the exception that I got after running app:

Caused by: android.database.sqlite.SQLiteException: no such table: recent (code 1): , while compiling: SELECT * FROM recent

It throws in this line:

Cursor cursor = database.rawQuery("SELECT * FROM recent", null);

Upvotes: 0

Views: 208

Answers (2)

Serafins
Serafins

Reputation: 1247

Firstly use Exception.

It's look like your table doesn't exist.

Upvotes: 0

Andrei B
Andrei B

Reputation: 2770

The table doesn't exist. You can catch the SQLiteException exception and if it triggers create the table and return TRUE (i.e. table is empty). Something like this

try {
    Cursor cursor = database.rawQuery("SELECT * FROM recent", null);
}
catch(SQLiteException e) {
    onCreate(database);
    return TRUE;
}

Upvotes: 1

Related Questions