xxxxxxxxxx
@Database(entities = {TableName.class}, version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
private static volatile MyDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public abstract TableNameDao TableNameDao();
static MyDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (MyDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
MyDatabase.class, "my_database")
.build();
}
}
}
return INSTANCE;
}
}
/*Let's walk through the code:
The database class for Room must be abstract and extend RoomDatabase
You annotate the class to be a Room database with @Database and use the annotation parameters to declare the entities that belong in the database and set the version number. Each entity corresponds to a table that will be created in the database. Database migrations are beyond the scope of this codelab, so we set exportSchema to false here to avoid a build warning. In a real app, you should consider setting a directory for Room to use to export the schema so you can check the current schema into your version control system.
The database exposes DAOs through an abstract "getter" method for each @Dao.
We've defined a singleton, MyDatabase, to prevent having multiple instances of the database opened at the same time.
getDatabase returns the singleton. It'll create the database the first time it's accessed, using Room's database builder to create a RoomDatabase object in the application context from the MyDatabase class and names it "my_database".
We've created an ExecutorService with a fixed thread pool that you will use to run database operations asynchronously on a background thread.
Note: When you modify the database schema, you'll need to update the version number and define a migration strategy
For a sample, a destroy and re-create strategy can be sufficient. But, for a real app, you must implement a migration strategy. See Understanding migrations with Room.
In Android Studio, if you get errors when you paste code or during the build process, select Build >Clean Project. Then select Build > Rebuild Project, and then build again. If you use the provided code, there should be no errors whenever you are instructed to build the app.*/