Java 类android.arch.persistence.room.Room 实例源码

项目:AndroidNewArchitectureExample    文件:AppModule.java   
@Provides
@Singleton
WeatherDAO provideWeatherDAO() {
    AppDatabase database = Room.databaseBuilder(context, AppDatabase.class, "data")
            //.addMigrations(MIGRATION_1_2)
            .build();

    // If no database found on the device, a new one created via analysing Entity interfaces.
    // Migrations aren't executed even when required schema version > 1.
    // It means migrations can't be used for populating db with data.
    // Hope they change this behaviour.
    Executors.newSingleThreadExecutor().execute(() -> {
        init(database.weatherDao());
    });

    return database.weatherDao();
}
项目:android-architecture-components    文件:AppDatabase.java   
/**
 * 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(final Context appContext,
        final AppExecutors executors) {
    return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME)
            .addCallback(new Callback() {
                @Override
                public void onCreate(@NonNull SupportSQLiteDatabase db) {
                    super.onCreate(db);
                    executors.diskIO().execute(() -> {
                        // Add a delay to simulate a long-running operation
                        addDelay();
                        // Generate the data for pre-population
                        AppDatabase database = AppDatabase.getInstance(appContext, executors);
                        List<ProductEntity> products = DataGenerator.generateProducts();
                        List<CommentEntity> comments =
                                DataGenerator.generateCommentsForProducts(products);

                        insertData(database, products, comments);
                        // notify that the database was created and it's ready to be used
                        database.setDatabaseCreated();
                    });
                }
            }).build();
}
项目:curbmap-android    文件:YourContributionsFragment.java   
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.your_contributions, container, false);

    AppDatabase db = Room.databaseBuilder(myView.getContext(),
            AppDatabase.class,
            "restrictions").allowMainThreadQueries().build();
    RestrictionDao restrictionDao = db.getRestrictionDao();
    Log.d(TAG, restrictionDao.getAll().toString());
    List<Restriction> listOfRestrictions = restrictionDao.getAll();

    //todo: sort by latest entries first
    String allCards = "";
    for (Restriction restriction : listOfRestrictions) {
        allCards += restriction.getCard() + "\n\n";
    }

    TextView yourContributions = (TextView) myView.findViewById(R.id.yourContributionsText);
    yourContributions.setText(allCards);

    return myView;
}
项目:react-native-caller-id-android    文件:DataBase.java   
public static DataBase getDatabase(Context context, String passPhrase) {
    prefs = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
    try {
        if (null == INSTANCE) {
            if (prefs.getBoolean("first", true) && null != passPhrase) {
                createNewKeys(context, getAlias(context));
                encryptString_old(context, getAlias(context), passPhrase);
            }

            String str = decryptString_old(context, getAlias(context));
            if(null == str) return null;

            SafeHelperFactory factory=SafeHelperFactory.fromUser(Editable.Factory.getInstance().newEditable(str));
            INSTANCE = Room.databaseBuilder(context, DataBase.class, "users").openHelperFactory(factory).allowMainThreadQueries().build();
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return INSTANCE;
}
项目:GmArchMvvm    文件:RepositoryManager.java   
@Override
public <DB extends RoomDatabase> DB obtainRoomDatabase(Class<DB> database, String dbName) {
    if (mRoomDatabaseCache == null) {
        mRoomDatabaseCache = mCacheFactory.build(CacheType.ROOM_DATABASE_CACHE_TYPE);
    }
    Preconditions.checkNotNull(mRoomDatabaseCache, "Cannot return null from a Cache.Factory#build(int) method");
    DB roomDatabase;
    synchronized (mRoomDatabaseCache) {
        roomDatabase = (DB) mRoomDatabaseCache.get(database.getName());
        if (roomDatabase == null) {
            RoomDatabase.Builder builder = Room.databaseBuilder(mApplication, database, dbName);
            //Customize the room configuration
            if (mRoomConfiguration != null) {
                mRoomConfiguration.configRoom(mApplication, builder);
            }
            roomDatabase = (DB) builder.build();
            mRoomDatabaseCache.put(database.getName(), roomDatabase);
        }
    }
    return roomDatabase;
}
项目:android-room-with-a-view    文件:WordRoomDatabase.java   
static WordRoomDatabase getDatabase(final Context context) {
    if (INSTANCE == null) {
        synchronized (WordRoomDatabase.class) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        WordRoomDatabase.class, "word_database")
                        // Wipes and rebuilds instead of migrating if no Migration object.
                        // Migration is not part of this codelab.
                        .fallbackToDestructiveMigration()
                        .addCallback(sRoomDatabaseCallback)
                        .build();
            }
        }
    }
    return INSTANCE;
}
项目:MVVMArms    文件:RepositoryManager.java   
@Override
public <DB extends RoomDatabase> DB obtainRoomDatabase(Class<DB> database, String dbName) {
    if (mRoomDatabaseCache == null) {
        mRoomDatabaseCache = mCacheFactory.build(CacheType.ROOM_DATABASE_CACHE_TYPE);
    }
    Preconditions.checkNotNull(mRoomDatabaseCache, "Cannot return null from a Cache.Factory#build(int) method");
    DB roomDatabase;
    synchronized (mRoomDatabaseCache) {
        roomDatabase = (DB) mRoomDatabaseCache.get(database.getName());
        if (roomDatabase == null) {
            RoomDatabase.Builder builder = Room.databaseBuilder(mApplication, database, dbName);
            //自定义 Room 配置
            if (mRoomConfiguration != null) {
                mRoomConfiguration.configRoom(mApplication, builder);
            }
            roomDatabase = (DB) builder.build();
            mRoomDatabaseCache.put(database.getName(), roomDatabase);
        }
    }
    return roomDatabase;
}
项目:justintrain-client-android    文件:AppDatabase.java   
public static AppDatabase getAppDatabase(Context context, boolean force) {
        if (INSTANCE == null || force) {

            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "justintrain.db")
                            // allow queries on the main thread.
                            // Don't do\ this on a real app! See PersistenceBasicSample for an example.
                            .openHelperFactory(new AssetSQLiteOpenHelperFactory())
//                            .addMigrations(MIGRATION_1_2)
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }
项目:android-ponewheel    文件:App.java   
private void initDatabase() {
    db = Room.databaseBuilder(getApplicationContext(),
            Database.class, "database-name-pow")
            .fallbackToDestructiveMigration()
            .build();
    dbExecutor = Executors.newSingleThreadExecutor();
}
项目:Android-ArchComponents    文件:MainActivityViewModel.java   
public LiveData<List<LocationInfo>> getLocationByUser(Context context, String user) {
    if (locationInfoList == null) {
        LocationInfoDatabase db = Room.databaseBuilder(context,
                LocationInfoDatabase.class, LocationDbKey.DATABASE_NAME).build();
        locationInfoList = db.locationInfoDao().getLocationByUser(user);
    }
    return locationInfoList;
}
项目:FitnessHabits    文件:FitnessHabitsApplication.java   
@MainThread
public AppDatabase getDatabase() {
    if (database == null) {
        database = Room.databaseBuilder(this, AppDatabase.class, "FitnessHabits-database").fallbackToDestructiveMigration().build(); //TODO: remove fallback destroy
    }
    return database;
}
项目:file.io-app    文件:UploadHistoryRoomDatabase.java   
public static UploadHistoryRoomDatabase getInstance(Context context) {
    if (INSTANCE == null) {
        synchronized (UploadHistoryRoomDatabase.class) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        UploadHistoryRoomDatabase.class,
                        "upload_history")
                        .build();
            }
        }
    }

    return INSTANCE;
}
项目:file.io-app    文件:UploadItemDaoTest.java   
@Before
public void initializeDb() {
    database = Room.inMemoryDatabaseBuilder(
            InstrumentationRegistry.getContext(),
            UploadHistoryRoomDatabase.class)
            .build();
}
项目:file.io-app    文件:UploadHistoryInstrumentedTest.java   
@Before
public void init() {
    database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), UploadHistoryRoomDatabase.class).build();
    for (int i = 0; i < 5; i++) {
        UploadItem uploadItem = new UploadItem("test file name " + i, "test URL " + i, Consts.DEFAULT_EXPIRE_WEEKS);
        database.uploadItemDao().insert(uploadItem);
    }

}
项目:labtablet    文件:AppDatabase.java   
public static AppDatabase getDatabase(Context context)
{
    if(INSTANCE == null)
    {
        INSTANCE = Room.databaseBuilder(context, AppDatabase.class, "LabTabletDB").build();
    }
    return INSTANCE;
}
项目:RoomDemo    文件:App.java   
@Override
public void onCreate() {
    super.onCreate();

    // create database
    database = Room.databaseBuilder(getApplicationContext(), MyDatabase.class, DATABASE_NAME)
            .addMigrations(MyDatabase.MIGRATION_1_2)
            .build();

    INSTANCE = this;
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();
    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:Hands-On-Android-UI-Development    文件:ClaimApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    DATABASE = Room.databaseBuilder(
            this, /* Context */
            ClaimDatabase.class, /* Abstract Database Class */
            "Claims" /* Filename */
    ).build();
}
项目:mapbox-plugins-android    文件:SearchHistoryDaoTest.java   
@Before
public void before() throws Exception {
  // using an in-memory database because the information stored here disappears when the
  // process is killed
  database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
    SearchHistoryDatabase.class)
    // allowing main thread queries, just for testing
    .allowMainThreadQueries()
    .build();

  searchHistoryDao = database.searchHistoryDao();
}
项目:mapbox-plugins-android    文件:SearchHistoryDatabase.java   
private static SearchHistoryDatabase buildDatabase(final Context appContext) {
  return Room.databaseBuilder(appContext, SearchHistoryDatabase.class, DATABASE_NAME).addCallback(
    new Callback() {
      @Override
      public void onCreate(@NonNull SupportSQLiteDatabase db) {
        super.onCreate(db);
        SearchHistoryDatabase database = SearchHistoryDatabase.getInstance(appContext);
        database.setDatabaseCreated();
      }
    }).build();
}
项目:LocationAware    文件:AppDataBase.java   
public static AppDataBase getInstance(Context context) {
  if (appDataBaseInstance == null) {
    appDataBaseInstance = Room.databaseBuilder(context, AppDataBase.class, DATABASE_NAME).build();
    appDataBaseInstance.recordItemDataSource =
        new CheckPointDataSource(appDataBaseInstance.checkPointDao());
  }
  return appDataBaseInstance;
}
项目:android-persistence    文件:AppDatabase.java   
public static AppDatabase getInMemoryDatabase(Context context) {
    if (INSTANCE == null) {
        INSTANCE =
                Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class)
                // To simplify the codelab, allow queries on the main thread.
                // Don't do this on a real app! See PersistenceBasicSample for an example.
                .allowMainThreadQueries()
                .build();
    }
    return INSTANCE;
}
项目:AndroidArchTodo    文件:AppDatabase.java   
/**
 * Get database instance
 * @param context Context of the application
 * @return instance of database
 */
public static AppDatabase getDatabase(Context context) {
    if (INSTANCE == null) {
        INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                AppDatabase.class,
                DATABASE_NAME).build();
    }
    return INSTANCE;
}
项目:BakingApp    文件:RecipesDatabase.java   
public static synchronized RecipesDatabase getRecipesDatabase(Context context){
    if (INSTANCE == null){
        INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                RecipesDatabase.class, "recipes")
                .build();
    }
    return INSTANCE;
}
项目:chaosflix    文件:ChaosflixViewModel.java   
public ChaosflixViewModel(Application application){
    super(application);
    Resources res = application.getResources();
    String recordingUrl = res.getString(R.string.api_media_ccc_url);
    String streamingUrl = res.getString(R.string.streaming_media_ccc_url);

    OkHttpClient client = new OkHttpClient();
    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create();
    RxJava2CallAdapterFactory rxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create();

    Retrofit retrofitRecordings = new Retrofit.Builder()
            .baseUrl(recordingUrl)
            .client(client)
            .addConverterFactory(gsonConverterFactory)
            .addCallAdapterFactory(rxJava2CallAdapterFactory)
            .build();
    recordingApi = retrofitRecordings.create(RecordingService.class);

    Retrofit retrofigStreaming = new Retrofit.Builder()
            .baseUrl(streamingUrl)
            .client(client)
            .addConverterFactory(gsonConverterFactory)
            .addCallAdapterFactory(rxJava2CallAdapterFactory)
            .build();
    streamingApi = retrofigStreaming.create(StreamingService.class);

    database = Room.databaseBuilder(getApplication().getApplicationContext(), ChaosflixDatabase.class, "mediaccc.db").build();
}
项目:RoomDemo2017    文件:RoomModule.java   
public RoomModule(Application application) {
    this.database = Room.databaseBuilder(
            application,
            ListItemDatabase.class,
            "ListItem.db"
    ).build();
}
项目:android-architecture-components    文件:MigrationTest.java   
private UsersDatabase getMigratedRoomDatabase() {
    UsersDatabase database = Room.databaseBuilder(InstrumentationRegistry.getTargetContext(),
            UsersDatabase.class, TEST_DB_NAME)
            .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_1_4)
            .build();
    // close the database and release any stream resources when the test finishes
    mMigrationTestHelper.closeWhenFinished(database);
    return database;
}
项目:android-architecture-components    文件:LocalUserDataSourceTest.java   
@Before
public void initDb() throws Exception {
    // using an in-memory database because the information stored here disappears when the
    // process is killed
    mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
            UsersDatabase.class).build();
    mDataSource = new LocalUserDataSource(mDatabase.userDao());
}
项目:android-architecture-components    文件:MigrationTest.java   
private UsersDatabase getMigratedRoomDatabase() {
    UsersDatabase database = Room.databaseBuilder(InstrumentationRegistry.getTargetContext(),
            UsersDatabase.class, TEST_DB_NAME)
            .addMigrations(MIGRATION_1_2)
            .build();
    // close the database and release any stream resources when the test finishes
    mMigrationTestHelper.closeWhenFinished(database);
    return database;
}
项目:android-architecture-components    文件:LocalUserDataSourceTest.java   
@Before
public void initDb() throws Exception {
    // using an in-memory database because the information stored here disappears when the
    // process is killed
    mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
            UsersDatabase.class).build();
    mDataSource = new LocalUserDataSource(mDatabase.userDao());
}
项目:android-architecture-components    文件:UserDaoTest.java   
@Before
public void initDb() throws Exception {
    // using an in-memory database because the information stored here disappears when the
    // process is killed
    mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
            UsersDatabase.class).build();
}
项目:android-architecture-components    文件:MigrationTest.java   
private UsersDatabase getMigratedRoomDatabase() {
    UsersDatabase database = Room.databaseBuilder(InstrumentationRegistry.getTargetContext(),
            UsersDatabase.class, TEST_DB_NAME)
            .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
            .build();
    // close the database and release any stream resources when the test finishes
    mMigrationTestHelper.closeWhenFinished(database);
    return database;
}
项目:android-architecture-components    文件:LocalUserDataSourceTest.java   
@Before
public void initDb() throws Exception {
    // using an in-memory database because the information stored here disappears when the
    // process is killed
    mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
            UsersDatabase.class).build();
    mDataSource = new LocalUserDataSource(mDatabase.userDao());
}
项目:android-architecture-components    文件:UsersDatabase.java   
public static UsersDatabase getInstance(Context context) {
    synchronized (sLock) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db")
                    .addMigrations(MIGRATION_1_2)
                    .build();
        }
        return INSTANCE;
    }
}
项目:android-architecture-components    文件:UsersDatabase.java   
public static UsersDatabase getInstance(Context context) {
    synchronized (sLock) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db")
                    .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                    .build();
        }
        return INSTANCE;
    }
}