1

In my app, I have implemented multiple content providers for a single db, one per table, as there are a lot of tables and having the logic of all of them in a single content provider is going to be quite messy.

I followed the advice given by Simo in this link:

Content provider for multiple tables

So there is an abstract AbsShopContentProvider that has a SQLiteOpenHelper member variable. This abstract content provider is then extended by multiple content providers like Table1Provider, Table2Provider,...

So now I have one instance of my SQLiteOpenHelper per Content Provider. Will this create any issues regarding thread safety?

Is it a good idea to make this SQLiteOpenhelper variable "static" in my abstract Content Provider and create an instance of it in onCreate() of the Abstract Provider only if it is null? Will it solve the issue of having many DB helper objects?

4

1 回答 1

2

您只需要确保共享一个实例SQLiteDatabase,SQLite 会自动处理同一数据库的锁定。

要使数据库全局可用,请扩展 Application 类:

public class App extends Application {
    private static SQLiteDatabase db;

    public static SQLiteDatabase getDb() {
        return db;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        db = new MySQLiteOpenHelper(getApplicationContext()).getWritableDatabase();
    }
}

并将其添加到清单中:

<application
    android:name=".App"

现在,您可以通过调用从任何 Activity/Fragment/Service 访问数据库App.getDb()

于 2013-07-28T10:51:09.523 回答