androidx.room.RoomDatabase Java Examples

The following examples show how to use androidx.room.RoomDatabase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DBUtil.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Performs the SQLiteQuery on the given database.
 * <p>
 * This util method encapsulates copying the cursor if the {@code maybeCopy} parameter is
 * {@code true} and either the api level is below a certain threshold or the full result of the
 * query does not fit in a single window.
 *
 * @param db          The database to perform the query on.
 * @param sqLiteQuery The query to perform.
 * @param maybeCopy   True if the result cursor should maybe be copied, false otherwise.
 * @param signal      The cancellation signal to be attached to the query.
 * @return Result of the query.
 */
@NonNull
public static Cursor query(@NonNull RoomDatabase db, @NonNull SupportSQLiteQuery sqLiteQuery,
        boolean maybeCopy, @Nullable CancellationSignal signal) {
    final Cursor cursor = db.query(sqLiteQuery, signal);
    if (maybeCopy && cursor instanceof AbstractWindowedCursor) {
        AbstractWindowedCursor windowedCursor = (AbstractWindowedCursor) cursor;
        int rowsInCursor = windowedCursor.getCount(); // Should fill the window.
        int rowsInWindow;
        if (windowedCursor.hasWindow()) {
            rowsInWindow = windowedCursor.getWindow().getNumRows();
        } else {
            rowsInWindow = rowsInCursor;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || rowsInWindow < rowsInCursor) {
            return CursorUtil.copyAndClose(windowedCursor);
        }
    }

    return cursor;
}
 
Example #2
Source File: StuffDatabase.java    From cwac-saferoom with Apache License 2.0 6 votes vote down vote up
static StuffDatabase create(Context ctxt, boolean memoryOnly, boolean truncate) {
  RoomDatabase.Builder<StuffDatabase> b;

  if (memoryOnly) {
    b=Room.inMemoryDatabaseBuilder(ctxt.getApplicationContext(),
      StuffDatabase.class);
  }
  else {
    b=Room.databaseBuilder(ctxt.getApplicationContext(), StuffDatabase.class,
      DB_NAME);
  }

  if (truncate) {
    b.setJournalMode(JournalMode.TRUNCATE);
  }

  b.openHelperFactory(SafeHelperFactory.fromUser(new SpannableStringBuilder("sekrit")));

  return(b.build());
}
 
Example #3
Source File: OpenScale.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
public void reopenDatabase(boolean truncate) throws SQLiteDatabaseCorruptException {
    if (appDB != null) {
        appDB.close();
    }

    appDB = Room.databaseBuilder(context, AppDatabase.class, DATABASE_NAME)
            .allowMainThreadQueries()
            .setJournalMode(truncate == true ? RoomDatabase.JournalMode.TRUNCATE : RoomDatabase.JournalMode.AUTOMATIC) // in truncate mode no sql cache files (-shm, -wal) are generated
            .addCallback(new RoomDatabase.Callback() {
                @Override
                public void onOpen(SupportSQLiteDatabase db) {
                    super.onOpen(db);
                    db.setForeignKeyConstraintsEnabled(true);
                }
            })
            .addMigrations(AppDatabase.MIGRATION_1_2, AppDatabase.MIGRATION_2_3, AppDatabase.MIGRATION_3_4, AppDatabase.MIGRATION_4_5)
            .build();
    measurementDAO = appDB.measurementDAO();
    userDAO = appDB.userDAO();
}
 
Example #4
Source File: LimitOffsetDataSource.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
protected LimitOffsetDataSource(RoomDatabase db, RoomSQLiteQuery query,
        boolean inTransaction, String... tables) {
    mDb = db;
    mSourceQuery = query;
    mInTransaction = inTransaction;
    mCountQuery = "SELECT COUNT(*) FROM ( " + mSourceQuery.getSql() + " )";
    mLimitOffsetQuery = "SELECT * FROM ( " + mSourceQuery.getSql() + " ) LIMIT ? OFFSET ?";
    mObserver = new InvalidationTracker.Observer(tables) {
        @Override
        public void onInvalidated(@NonNull Set<String> tables) {
            invalidate();
        }
    };
    db.getInvalidationTracker().addWeakObserver(mObserver);
}
 
Example #5
Source File: DB.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static RoomDatabase.Builder<DB> getBuilder(Context context) {
    try {
        ReLinker.log(new ReLinker.Logger() {
            @Override
            public void log(String message) {
                Log.i("Relinker: " + message);
            }
        }).loadLibrary(context, "sqlite3x");
    } catch (Throwable ex) {
        Log.e(ex);
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    int threads = prefs.getInt("query_threads", 4); // AndroidX default thread count: 4
    Log.i("Query threads=" + threads);
    ExecutorService executor = Helper.getBackgroundExecutor(threads, "query");

    return Room
            .databaseBuilder(context, DB.class, DB_NAME)
            .openHelperFactory(new RequerySQLiteOpenHelperFactory())
            .setQueryExecutor(executor)
            .setJournalMode(JournalMode.WRITE_AHEAD_LOGGING) // using the latest sqlite
            .addCallback(new Callback() {
                @Override
                public void onOpen(@NonNull SupportSQLiteDatabase db) {
                    Log.i("Database version=" + db.getVersion());

                    createTriggers(db);
                }
            });
}
 
Example #6
Source File: LimitOffsetDataSource.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
protected LimitOffsetDataSource(RoomDatabase db, SupportSQLiteQuery query,
        boolean inTransaction, String... tables) {
    this(db, RoomSQLiteQuery.copyFrom(query), inTransaction, tables);
}
 
Example #7
Source File: DBUtil.java    From FairEmail with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Performs the SQLiteQuery on the given database.
 * <p>
 * This util method encapsulates copying the cursor if the {@code maybeCopy} parameter is
 * {@code true} and either the api level is below a certain threshold or the full result of the
 * query does not fit in a single window.
 *
 * @param db          The database to perform the query on.
 * @param sqLiteQuery The query to perform.
 * @param maybeCopy   True if the result cursor should maybe be copied, false otherwise.
 * @return Result of the query.
 *
 * @deprecated This is only used in the generated code and shouldn't be called directly.
 */
@Deprecated
@NonNull
public static Cursor query(RoomDatabase db, SupportSQLiteQuery sqLiteQuery, boolean maybeCopy) {
    return query(db, sqLiteQuery, maybeCopy, null);
}