Android Room Persistence Library Database tutorial

Published by inkskull on

Android Room Persistence Library Database tutorial

This Tutorial shows how can we implement Android Room Persistence Library Database tutorial in Android studio.

The Older SQLite have some of these Disadvantages For Overcoming Android introduced Android Room Database for Handling data on Android Devices.

  • In Older SQLite databases we use A lot of boilerplate code for database operations, especially for querying.
  • No compile-time checks (e.g. SQL queries) in Normal SQLite Databases in Android this can be replaced by Room Persistence.
  • Manual schema updates (maintenance, migration scripts), SQLite Database migration is too difficult and it can be overcome by Using Android Persistence Library.

The Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Android highly recommend using Room instead of SQLite. However, if you prefer to use SQLite APIs to work with your app’s databases, Android still supports direct database access using SQLite.

There are three major components in Room:

  • Database:-Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.
  • Entity:-Represents a table within the database.
  • Dao:-Contains the methods used for accessing the database.

The class that’s annotated with should@Database satisfy the following conditions: Be an abstract class that extends.RoomDatabaseInclude the list of entities associated with the database within the annotation.Contain a constructor that has noarguments and returns the class that is annotated with.@DaoAt runtime, you can acquire an instance of Database calling orRoom.databaseBuilder()Room.inMemoryDatabaseBuilder().

 

Room Database Architecture

1) Adding Maven repository to your build.gradle, Your build.gradle project file should be defined in this way:

allprojects {
    repositories {
        jcenter()
        google()
    }
}

2) Adding Gradle dependencies

Now, you have to add the Room dependencies on your build.gradle file of your module inside of dependency group:

dependencies {
    compile 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}

For room, database Release notes Here

3)Now create an entity called Student. It defines attributes of your table and must to declare one field as primary key. It has an annotation to auto-generate or the user can give values. Student is annotated with @Entity and it is the name of the table or we can manually give Table name like @Entity(tableName= “Student”). To make field primary key, Need to annotate a field with @PrimaryKey and property autoGenerate which assign automatic IDs like below or user can assign primary key values manually.

@PrimaryKey(autoGenerate = true)
private long studentId;

4) Must create a default constructor  and  add Setters and getters to access values in entity otherwise shows error

The room will create a user table with defined attributes.

package com.cretlabs.roomdatabase.entities;

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;

/**
 * Created by Gokul on 2/18/2018.
 */
@Entity( tableName = "Student")
public class Student {
    @NonNull
    @PrimaryKey(autoGenerate = true)
    private long studentId;
    public Student() {
    }
    private long classId;
    private String studentName;
    private String studentAddress;

    public Student(@NonNull long studentId, long classId, String studentName, String studentAddress) {
        this.studentId = studentId;
        this.classId = classId;
        this.studentName = studentName;
        this.studentAddress = studentAddress;
    }

    @NonNull
    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(@NonNull long studentId) {
        this.studentId = studentId;
    }

    public long getClassId() {
        return classId;
    }

    public void setClassId(long classId) {
        this.classId = classId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentAddress() {
        return studentAddress;
    }

    public void setStudentAddress(String studentAddress) {
        this.studentAddress = studentAddress;
    }
}

 

4) Create a @Dao interface with name StudentDao. This interface is annotated with @Dao annotation. The room will generate an implementation of all defined methods. There are four annotations @Query@Insert@Update@Deleteto perform CRUD operations. @Query annotation is used to perform normal SQLite queries on the database.

package com.cretlabs.roomdatabase.dao;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import com.cretlabs.roomdatabase.entities.Student;

import java.util.List;

import static android.arch.persistence.room.OnConflictStrategy.IGNORE;

/**
 * Created by Gokul on 2/18/2018.
 */
@Dao
public interface StudentDao {

    @Query("SELECT * FROM Student")
    List<Student> getAllStudents();

    @Query("SELECT * FROM Student WHERE  studentId= :studentId")
    Student loadStudentById(long studentId);

    @Query("SELECT * FROM Student where studentName = :studentName ")
    List<Student> findStudentByName(String studentName);

    @Insert(onConflict = IGNORE)
    void insertStudent(Student student);

    @Insert(onConflict = IGNORE)
    void insertMultipleRecord(List<Student> students);

    @Delete
    void deleteStudent(Student student);
}

5) Create a RoomDatabase class to implement functionalities to create Room Database in Android.Need to add created entities to this class with annotation @Database, Give version to more further schema updation  in future

@Database(entities = {Student.class}, version = 1)

Showing the full code in RoomDatabase class.

package com.cretlabs.roomdatabase.database;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.content.Context;

import com.cretlabs.roomdatabase.dao.ClassStudentDao;
import com.cretlabs.roomdatabase.dao.SchoolDao;
import com.cretlabs.roomdatabase.dao.StudentDao;
import com.cretlabs.roomdatabase.entities.ClassStudent;
import com.cretlabs.roomdatabase.entities.School;
import com.cretlabs.roomdatabase.entities.Student;

@Database(entities = {Student.class}, version = 1)
public abstract class RoomDatabase extends android.arch.persistence.room.RoomDatabase {

    private static RoomDatabase INSTANCE;

    public abstract StudentDao studentDao();

    public static RoomDatabase getDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context, RoomDatabase.class,"School_DB")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

 

6) Create a DataInitializer class to insert sample datas to Room database

 

package com.cretlabs.roomdatabase.database;

import android.os.AsyncTask;

import com.cretlabs.roomdatabase.entities.ClassStudent;
import com.cretlabs.roomdatabase.entities.School;
import com.cretlabs.roomdatabase.entities.Student;

import java.util.ArrayList;
import java.util.List;

public class DataInitializer {

    public static void AddSampleDataAsync(final AppDatabase db) {
        PopulateSampleDbAsync task = new PopulateSampleDbAsync(db);
        task.execute();
    }

    private static void populateSampleData(AppDatabase db) {
  
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(21, 10, "Student 1", "Student Address 1"));
        studentList.add(new Student(22, 10, "Student 2", "Student Address 2"));
        studentList.add(new Student(23, 10, "Student 3", "Student Address 3"));

        studentList.add(new Student(24, 11, "Student 4", "Student Address 4"));
        studentList.add(new Student(25, 11, "Student 5", "Student Address 5"));
        studentList.add(new Student(26, 11, "Student 6", "Student Address 6"));

        studentList.add(new Student(27, 12, "Student 7", "Student Address 7"));
        studentList.add(new Student(28, 12, "Student 8", "Student Address 8"));
        studentList.add(new Student(29, 12, "Student 9", "Student Address 9"));

        studentList.add(new Student(30, 13, "Student 10", "Student Address 10"));
        studentList.add(new Student(31, 13, "Student 11", "Student Address 11"));
        studentList.add(new Student(32, 13, "Student 12", "Student Address 12"));

        studentList.add(new Student(30, 14, "Student 13", "Student Address 13"));
        studentList.add(new Student(31, 14, "Student 14", "Student Address 14"));
        studentList.add(new Student(32, 14, "Student 15", "Student Address 15"));

        studentList.add(new Student(30, 15, "Student 16", "Student Address 16"));
        studentList.add(new Student(31, 15, "Student 17", "Student Address 17"));
        studentList.add(new Student(32, 15, "Student 18", "Student Address 18"));
        db.studentDao().insertMultipleRecord(studentList);
    }

    private static class PopulateSampleDbAsync extends AsyncTask<Void, Void, Void> {

        private final AppDatabase mDb;

        PopulateSampleDbAsync(AppDatabase db) {
            mDb = db;
        }

        @Override
        protected Void doInBackground(final Void... params) {
            populateSampleData(mDb);
            return null;
        }
    }
}

7) Create  an activity to create the database, insert dummy values

public class MainActivity extends AppCompatActivity {
    private AppCompatTextView mDataappCompatTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppDatabase appDatabase = AppDatabase.getDatabase(MainActivity.this);
        //inserting sample data
        DataInitializer.AddSampleDataAsync(appDatabase);
     
    }
}

Download Full Source Code From Github

Keep following thoughtnerds for upcoming Android Room Persistence Library Advanced Database tutorial

Thank you.Happy Coding 😀

Categories: Android

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com