Created
March 30, 2019 09:42
-
-
Save magdamiu/819797a5b212bee5d8671dc24fdaa65d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Database(entities = {Item.class}, version = 1, exportSchema = false) | |
public abstract class ItemRoomDatabase extends RoomDatabase { | |
public abstract ItemDao itemDao(); | |
private static ItemRoomDatabase INSTANCE; | |
static ItemRoomDatabase getDatabase(final Context context) { | |
if (INSTANCE == null) { | |
synchronized (ItemRoomDatabase.class) { | |
if (INSTANCE == null) { | |
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), | |
ItemRoomDatabase.class, "item_database") | |
// Wipes and rebuilds instead of migrating if no Migration object. | |
// Migration is not part of this codelab. | |
.fallbackToDestructiveMigration() | |
.addCallback(sRoomDatabaseCallback) | |
.build(); | |
} | |
} | |
} | |
return INSTANCE; | |
} | |
/** | |
* Override the onOpen method to populate the database. | |
* For this sample, we clear the database every time it is created or opened. | |
*/ | |
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){ | |
@Override | |
public void onOpen (@NonNull SupportSQLiteDatabase db){ | |
super.onOpen(db); | |
// If you want to keep the data through app restarts, | |
// comment out the following line. | |
new PopulateDbAsync(INSTANCE).execute(); | |
} | |
}; | |
/** | |
* Populate the database in the background. | |
* If you want to start with more items, just add them. | |
*/ | |
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> { | |
private final ItemDao mDao; | |
String [] items = {"dolphin", "crocodile", "cobra"}; | |
PopulateDbAsync(ItemRoomDatabase db) { | |
mDao = db.itemDao(); | |
} | |
@Override | |
protected Void doInBackground(final Void... params) { | |
// Start the app with a clean database every time. | |
// Not needed if you only populate on creation. | |
mDao.deleteAll(); | |
for( int i = 0; i <= items.length - 1; i++) { | |
Item item = new Item(items[i]); | |
mDao.insert(item); | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment