0

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!

Community
  • 1
  • 1
  • "...not sure if that's the correct way." - I would have to say, it's definitely not. If it's your database, you know when transactions are happening. Check the count whenever you perform a delete. You don't need a `Service`. – Mike M. Mar 30 '16 at 06:12
  • http://stackoverflow.com/questions/17034511/android-database-sqlite-sqlitecantopendatabaseexception-unknown-error-code-14 – sasikumar Mar 30 '16 at 06:12
  • 1
    you are not closing your `mcursor` – pskink Mar 30 '16 at 06:14
  • @MikeM. I'm certain a service is needed, because I need to run those functions in the background without affecting the Main thread. What I meant from "not sure if that's the correct way." was about my approach for making the Service always active. – OrangePeel Mar 30 '16 at 06:45
  • @OrangePeel "I'm certain a service is needed..." - No, it's really not. You should be doing all of your transactions on a separate thread anyway. Adding a count query after a delete is trivial. I'm sorry, but your design is overly complicated, and needlessly costly. – Mike M. Mar 30 '16 at 06:58

0 Answers0