What about multithreading in Android SQLite?

前端 未结 6 1152
旧巷少年郎
旧巷少年郎 2021-02-05 16:06

In my app I\'ve got to implement some UI and Sync service. It runs in the background and updates data. Sync service is not very simple, it uses multithreading.

So, here

6条回答
  •  梦谈多话
    2021-02-05 16:34

    Well, reading the documentation my previous answer seems incorrect. I have a single(ton) SQLiteOpenHelper, so it seems all connections are the same. Even the readable ones are the same as the writable connections.

    So I am going to skip calling getReadableDatabase, and use getWritableDatabase only. Then I am going to keep a counter, to make sure the database get closed once and only once.

    Since the SQLiteOpenHelper serializes the writes, everything should be fine this way. I will just have to keep track of the connection, to make sure I dont keep one open at the end.

    So in my DbHelper class I now have:

    private int activeDatabaseCount = 0;
    public synchronized SQLiteDatabase openDatabase() {
        SQLiteDatabase connection = getWritableDatabase(); // always returns the same connection instance
        activeDatabaseCount++;
        return connection; 
    }
    public synchronized void closeDatabase(SQLiteDatabase connection) {
        activeDatabaseCount--;
        if (activeDatabaseCount == 0) {
            if (connection != null) {
                if (connection.isOpen()) {
                    connection.close();
                }
            }
        }
    }
    

提交回复
热议问题