You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.0 KiB
63 lines
2.0 KiB
5 years ago
|
package com.community.pocket.util;
|
||
|
|
||
|
import android.content.Context;
|
||
|
|
||
|
import androidx.lifecycle.LiveData;
|
||
|
import androidx.lifecycle.MutableLiveData;
|
||
|
import androidx.room.Database;
|
||
|
import androidx.room.Room;
|
||
|
import androidx.room.RoomDatabase;
|
||
|
|
||
|
import com.community.pocket.data.dao.TokenDao;
|
||
|
import com.community.pocket.data.model.Token;
|
||
|
|
||
|
@Database(entities = {Token.class}, version = 1, exportSchema = false)
|
||
|
public abstract class AppDatabase extends RoomDatabase {
|
||
|
public abstract TokenDao tokenDao();
|
||
|
|
||
|
private static AppDatabase sInstance;
|
||
|
|
||
|
public static final String DATABASE_NAME = "basic-sample-db";
|
||
|
|
||
|
private final MutableLiveData<Boolean> mIsDatabaseCreated = new MutableLiveData<>();
|
||
|
|
||
|
public static AppDatabase getInstance(Context context) {
|
||
|
if (sInstance == null) {
|
||
|
synchronized (AppDatabase.class) {
|
||
|
if (sInstance == null) {
|
||
|
sInstance = buildDatabase(context.getApplicationContext());
|
||
|
sInstance.updateDatabaseCreated(context.getApplicationContext());
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return sInstance;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Build the database. {@link Builder#build()} only sets up the database configuration and
|
||
|
* creates a new instance of the database.
|
||
|
* The SQLite database is only created when it's accessed for the first time.
|
||
|
*/
|
||
|
private static AppDatabase buildDatabase(Context appContext) {
|
||
|
return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME)
|
||
|
.build();
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Check whether the database already exists and expose it via {@link #getDatabaseCreated()}
|
||
|
*/
|
||
|
private void updateDatabaseCreated(final Context context) {
|
||
|
if (context.getDatabasePath(DATABASE_NAME).exists()) {
|
||
|
setDatabaseCreated();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private void setDatabaseCreated() {
|
||
|
mIsDatabaseCreated.postValue(true);
|
||
|
}
|
||
|
|
||
|
public LiveData<Boolean> getDatabaseCreated() {
|
||
|
return mIsDatabaseCreated;
|
||
|
}
|
||
|
}
|