Reputation: 367
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?
Upvotes: 1
Views: 3267
Reputation: 29436
All you need is to make sure that you share one instance of SQLiteDatabase
, SQLite automatically takes care of locking for same database.
To make a database globally available, extend Application class:
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();
}
}
and add it to manifest:
<application
android:name=".App"
Now, you can access the database from any Activity/Fragment/Service by calling App.getDb()
Upvotes: 2