开发者

Preventing db lock exceptions when opening

开发者 https://www.devze.com 2023-03-21 06:17 出处:网络
I have an app that uses a database with 3 tables in it.Those 3 tables have data read from and written to them by activities and services.

I have an app that uses a database with 3 tables in it. Those 3 tables have data read from and written to them by activities and services.

Having gotten a few "android.database.sqlite.SQLiteException: database is locked" crashes, I went in to the database adapter class and wrapped every write, update, or delete function with a synchronized statement, so like:

public int deleteExpiredAlarms() {
    String whereClause = FIELD_EXPIRED + " = 1";

    int val = 0;
    synchronized(dbWriteLock) {
        val = db.delete(ALARM_DATABASE_TABLE, whereClause, null);
    }
    return val;
}

That seemed to make it better. But lately it's gotten bad again as I've added more services that read and write to different tables.

  1. Do I need to synchronize ALL db access statements, including queries?
  2. The exception is occurring on the attempt to open the writable database via the open helper...should I synchronize that act also?
  3. I've heard that I should only be using one db helper so that there won't be issues with multiple threads accessing the db. How do I use only one db helper? Every example I've seen so far has the db helper as an instantiated value inside the db adapter....so wouldn't that be a separate db helper per db adapter instantiated (one in an activity, one in a service running,etc)

I've looked at using a content provider instead, as开发者_JAVA技巧 it's been claimed to solve problems like this, but it's really more work than I want to do if I should be able to have direct db access without locking issues. And I do not plan to make this db accessible to other apps.

Thanks for the help.

0

精彩评论

暂无评论...
验证码 换一张
取 消