Month: December 2017

Room Library Sample App-easier alternative to SQlite !

Recently, I developed my own app “SaveThePassword” which helps me store all my user ids and passwords for different apps and websites that I have an account with. This gave me an opportunity to explore and work with Room Persistence Library (released by Google in 2017 as part of their Architecture components), A library that provides an abstraction layer over SQLite to allow fluent database access in your android app.

Below I am demonstrating a simple app that uses room library to store a Person’s details including name and age.

  • In Project Build.gradle, add the following maven repository:
    allprojects {
        repositories {
            maven { url 'https://maven.google.com' }
  • In Module Build.gradle, add the following dependencies:
    dependencies {
        compile 'android.arch.persistence.room:runtime:1.0.0'
        annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
        testImplementation "android.arch.persistence.room:testing:1.0.0"
  • Click Sync now.
  • Create a new Entity file Person.java, annotating it with @Entity. This represents the table within the database. It is a necessity to declare which field will be the primary key for the table.
    @Entity
    public class Person {
        public Person(String name, int age)
        {
            this.name = name;
            this.age = age;
        }
        @NonNull
        public String getName() {
            return name;
        }
        public void setName(@NonNull String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @PrimaryKey @NonNull
        public String name;
        public int age;
    }
  • Now create the public interface DAO(Data Access Object) PersonDao.java , which contains different methods to access the Person Entity created earlier in the database.
    @Dao
    public interface PersonDao {
        @Insert
        void InsertPerson(Person password);
        @Query("SELECT * FROM Person")
        List getAll();
    }
  • Create AppDatabase class which extends RoomDatabase . Its purpose is to contain the database holder and serve as the main access point
    @Database(entities = {Person.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
        private static AppDatabase INSTANCE;
        public abstract PersonDao personDao();
    
        public static AppDatabase getAppDatabase(Context context) {
            if (INSTANCE == null) {
                INSTANCE =
                        Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database").allowMainThreadQueries().build();
            }
            return INSTANCE;
        }
        public static void destroyInstance() {
            INSTANCE = null;
        }
    }
  • In the layout file for MainActivity, activity_main.xml, add two edit texts for user to enter person name and age and a button, the click of which will save the Person to the Database.
  • In the Main Activity, get the instance of the database, and call the respective Dao method on the click of the save button to save the User entered person details to the database.
    db = AppDatabase.getAppDatabase(getApplicationContext());
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            db.personDao().InsertPerson(new Person(name.getText().toString(), Integer.parseInt(age.getText().toString())));
        }
    });
  • Similarly, other queries can be specified in the Dao class and used anywhere in the application to access the underlying database.

Sample code is available on github.