Author : Ajin K Augustine

Published on: January 24, 2018

Category : Technical Feed

It’s not a big task for an Android developer to convert raw data into structured database for internal storage. This is done using the most reliable language – SQL. The inbuilt SQLite core library within the Android OS will handle CRUD (Create, Read, Update and Delete) operations required for a database. Java classes and interfaces for SQLite provided by android.database.sqlite maintains an effective database management system. But this conventional method has its own disadvantages.
 
  • It is required to write long repetitive code which will be time consuming as well as erring.
  •  It is very difficult to manage SQL queries for a complex relational database.
To overcome this, Google has introduced Room Persistence Library which acts as an abstraction layer for the existing SQLite API’s. All the required packages, parameters, methods and variables are imported to an Android project by using simple annotations.
Room Persistence Library

Annotations in Room Persistence Library

Annotations Purpose
@Entity Creates a SQLite table in the database using a data model class.
@Dao Create a Data Access Object in the database using an interface class.
@Database A class with this annotation will create an abstraction for the Data Access Object.
@PrimaryKey A variable with this annotation will set a primary key for the table.
@Insert Inserts parameters into the table.
@Update Updates parameters of an existing table.
@Delete Deletes parameters of an existing table
@Query Running SQL query method within the table
@Ignore Ignores the parameter form the Room database

Let’s have a look on how to implement this with an example.

1. Add the gradle dependencies in build.gradle file.

implementation “android.arch.persistence.room:runtime:1.0.0”
annotationProcessor “android.arch.persistence.room:compiler:1.0.0”

2. Create a data model class for database table and annotate its table name and primary key.

@Entity
 public class Movies {
    @NonNull
    @PrimaryKey
     private String movieId;
     private String movieName;

     public Movies() {
     }

      public String getMovieId() { return movieId; }
      public void setMovieId(String movieId) { this.movieId = movieId; }
      public String getMovieName() { return movieName; }
  public void setMovieName (String movieName) { this.movieName = movieName; }

}

3. Create an interface class for Database access. Create abstract methods for CRUD operations. Add custom SQL query as a method.

@Dao
public interface DaoAccess {

     @Insert
     void insertOnlySingleMovie (Movies movies);
     @Insert
     void insertMultipleMovies (List<Movies> moviesList);
     @Query (SELECTFROM Movies WHERE movieId = :movieId)
     Movies fetchOneMoviesbyMovieId (int movieId);
     @Update
     void updateMovie (Movies movies);
     @Delete
     void deleteMovie (Movies movies);
}

4. Create a Database class for database implementation.

@Database (entities = {Movies.class}, version = 1, exportSchema = false)
public abstract class MovieDatabase extends RoomDatabase {
   public abstract DaoAccess daoAccess() ;
}

5.Declare and initialize object for the Database class in your Activity or Fragment class.

private static final String DATABASE_NAME = “movies_db”;
private MovieDatabase movieDatabase;
movieDatabase =       Room.databaseBuilder(getApplicationContext(),
                                       MovieDatabase.class, DATABASE_NAME)
                                       .fallbackToDesctructiveMigration()
                                       .build();

Initial steps are done. By using the database object, you can do all functionalities for database management.

Sample Insert code:-

new Thread(new Runnable() {
     @Override
      public void run() {
          Movies movie =new Movies();
          movie.setMovieId( “2”);
          movie.setMovieName(“The Prestige”);
          movieDatabase.daoAccess () . insertOnlySingleMovie (movie);
     }
}
) .start();

Always use a Thread , AsyncTask or any worker threads to perform database operations.

For further queries, please refer: https://developer.android.com/training/data-storage/room/index.html

Experience seamless coding, now that there’s ROOM for improvement!

Looking for an overview on Android Studio 3.0? Our blog A Quick Look at Android Studio 3.0 can help!

FacebooktwitterlinkedinFacebooktwitterlinkedin

Tags: