Android: Save Data in local Db using Android Room


Save Data in local Db using Android Room

Room in Android App development is a persistence library (just like an ORM tool JPA/Hibernate) that provides an abstraction layer over SQLite Database, thus this give you a benefit of an easy seamless database access without compromising the the full power of SQLite. It is recommended to make use of the Room instead of directly using SQLite because of the below reasons,

  • Do compile time verification of your SQL queries.
  • Streamline the migration path of your database.
  • Make use of annotations that help to reduce boilerplate code and thus errors resulting from it.
  • Easy seamless database access without compromising the the full power of SQLite

Tutorial: Setting up Room in Android Project

  • Setting up Gradle: Add the dependency in build.gradle,
    dependencies {
    
    ....
    
        implementation "androidx.room:room-runtime:2.4.1"
        annotationProcessor "androidx.room:room-compiler:2.4.1"
    
    ....
    
    }
  • Create the Entity classes,
    @Entity
    public class Employee {
        @PrimaryKey
        public int emp_id;
    
        @ColumnInfo(name = "emp_name")
        public String empName;
    
        @ColumnInfo(name = "emp_dept")
        public String empDept;
    
        @ColumnInfo(name = "emp_sal")
        public Double empSal;
    }
  • Creating the DAO layer,
    @Dao
    public interface EmployeeDao {
        @Query("SELECT * FROM employee")
        List< Employee > getAll();
    
        @Query("SELECT * FROM employee WHERE emp_id IN (:empIds)")
        List<Employee> loadAllByEmpIds(int[] empIds);
    
        @Query("SELECT * FROM employee WHERE emp_name LIKE :empName LIMIT 1")
        Employee findByEmpName(String firstName);
    
        @Insert
        void insertAll(Employee... employee);
    
        @Delete
        void delete(Employee employee);
    }
  • Create the app database: You must extend RoomDatabase and annotate the class with @Database

    @Database(entities = {Employee.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
        public abstract EmployeeDao employeeDao();
    }

How to use The Room Database in your Android Application

Now that we have set the DAO, DAO implementation and the Database, lets use it in your Intents,



AppDatabase appDb = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();

EmployeeDao empDao = db.empDao();

Employee empDetails = findByEmpName("Sam");
List<Employee> employees = empDao.getAll();


Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap