mardi 29 mars 2016

cursor.getcount repeatedly for an empty table

I have an android app which always runs an Intent Service in the background. I also have a database. My service continually checks whether a table in the DB is empty or not. If it is populated, it performs the required functions. To do this, I am counting the number of rows in the table :

public int getCount(){
    SQLiteDatabase db = this.getWritableDatabase();
    String count = "SELECT count(*) FROM Queue;";
    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    db.close();
    return icount;
}

This works perfectly fine when the table is populated. But for an empty case, it does count the number of rows as 0(checked in log) but after several times, my app crashes :

03-30 01:43:45.465 2026-2055/? E/SQLiteLog﹕ (14) statement aborts at 7: [SELECT count(*) FROM Queue;] unable to open database file

03-30 01:43:45.465 2026-2055/? E/SQLiteQuery﹕ exception: unable to open database file (code 14); query: SELECT count(*) FROM Queue;

03-30 01:43:45.465 2026-2055/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[MyService]

android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file (code 14)

at DATA.QueueTable.getCount(QueueTable.java:29)

Which is:

mcursor.moveToFirst();

Here is my Service:

 protected void onHandleIntent(Intent intent) {
    Log.d("tracing","Starting background service");
    int count=0;
    String c;
    while(true){
        count = queueTable.getCount();
        c = String.valueOf(count);
        Log.d("tracing",c);
        if(count>0){/* function */}
    }
}

NOTE: I just want to count the number of rows for an empty table here. And I'm using an infinite while loop to ensure my service always runs, not sure if that's the correct way. :3

Thank you for your help!

Aucun commentaire:

Enregistrer un commentaire