Android Developers
Published in

Android Developers

Take the 7 steps to Room (Source)

7 Steps To Room

  1. sqlite — Uses SQLiteOpenHelper and traditional SQLite interfaces.
  2. room — Replaces implementation with Room and provides migrations.

Step 1 — Update the gradle dependencies

allprojects {
repositories {
google()
jcenter()
}
}
ext {
...
roomVersion = '1.0.0-alpha4'
}
dependencies{
implementation
“android.arch.persistence.room:runtime:$rootProject.roomVersion”
annotationProcessor
“android.arch.persistence.room:compiler:$rootProject.roomVersion”
androidTestImplementation
“android.arch.persistence.room:testing:$rootProject.roomVersion”
}
android {
defaultConfig {
...
// used by Room, to test migrations
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
}

// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs +=
files("$projectDir/schemas".toString())
}
...

Step 2 — Update model classes to entities

  • Annotate the class with @Entity and use the tableName property to set the name of the table.
  • Set the primary key by adding the @PrimaryKey annotation to the correct fields — in our case, this is the ID of the User.
  • Set the name of the columns for the class fields using the @ColumnInfo(name = “column_name”) annotation. Feel free to skip this step if your fields already have the correct column name.
  • If multiple constructors are suitable, add the @Ignore annotation to tell Room which should be used and which not.
@Entity(tableName = "users")
public class User {

@PrimaryKey
@ColumnInfo(name = "userid")
private String mId;

@ColumnInfo(name = "username")
private String mUserName;

@ColumnInfo(name = "last_update")
private Date mDate;

@Ignore
public User(String userName) {
mId = UUID.randomUUID().toString();
mUserName = userName;
mDate = new Date(System.currentTimeMillis());
}

public User(String id, String userName, Date date) {
this.mId = id;
this.mUserName = userName;
this.mDate = date;
}
...
}

Step 3 — Create Data Access Objects (DAOs)

@Query(“SELECT * FROM Users”)
List<User> getUsers();

Step 4 — Create the database

@Database(entities = {User.class}, version = 2)
@TypeConverters(DateConverter.class)
public abstract class UsersDatabase extends RoomDatabase {

private static UsersDatabase INSTANCE;

public abstract UserDao userDao();
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
database = Room.databaseBuilder(context.getApplicationContext(),
UsersDatabase.class, "Sample.db")
.addMigrations(MIGRATION_1_2)
.build();

Step 5 — Update the Repository to use Room

public List<User> getUsers() {
return mUserDao.getUsers();
}
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Step 6 — On-device testing

Testing UserDao

@Before
public void initDb() throws Exception {
mDatabase = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getContext(),
UsersDatabase.class)
.build();
}
@After
public void closeDb() throws Exception {
mDatabase.close();
}
@Test
public void insertAndGetUser() {
// When inserting a new user in the data source
mDatabase.userDao().insertUser(USER);

//The user can be retrieved
List<User> users = mDatabase.userDao().getUsers();
assertThat(users.size(), is(1));
User dbUser = users.get(0);
assertEquals(dbUser.getId(), USER.getId());
assertEquals(dbUser.getUserName(), USER.getUserName());
}

Testing the UserDao usage in LocalUserDataSource

@Before
public void initDb() throws Exception {
mDatabase = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getContext(),
UsersDatabase.class)
.build();
mDataSource = new LocalUserDataSource(mDatabase.userDao());
}

Testing the database migration

Step 7 — Cleanup

--

--

Articles on modern tools and resources to help you build experiences that people love, faster and easier, across every Android device.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store