I am trying to migrate a project to Android Room. After reading the Android Room documentation I noticed that a Singleton is suitable for accessing my database.
Quote from Android Developer:
Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.
I wrote the following piece of code:
@Database(entities = {Category.class, News.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static final String DB_NAME = "database.db";
private static AppDatabase instance;
public abstract CategoryDao categoryDao();
public abstract NewsDao newsDao();
private AppDatabase () {}
public static AppDatabase getInstance(Context context) {
if (instance == null) {
synchronized (AppDatabase.class) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DB_NAME).build();
}
}
}
return instance;
}
}
Just a simple double checking locking Singleton.
I have read some guides/tutorials and almost everyone comes with a similar approach, however I can see some problems with this approach:
- Need to pass a
Context
every single time, even only you need it one time to initialize the Singleton. - What if I need to access the database without a
Context
available? - It's even admissible to send parameters to a Singleton?
Any ideas how to implement a Room Database Singleton that solves these problems?
I would like to avoid DI libraries like Dagger2 if possible.