room database architecture

Improve App Performance with Room Database Architecture

Android Architecture components, including Room database architecture, are integral to Android Jetpack. Android Jetpack components, leveraging Kotlin language features, enhance productivity. 

 These software components have been organized in four categories in which one of the categories is Architecture components. Other are foundation components, behavior components, and UI components. 

These Android components are a collection of libraries that helps in doing the following: 

  • Developing the robust Android Application
  • Developing the testable Android Application
  • Developing the maintainable Android Applications 
  • Managing UI components lifecycle
  • Handling data persistence

Android Architecture Components

All the Android architecture components are as follows:

  • Data Binding: Helps in declaratively binding UI elements in our layout to data sources of the app.
  •  Lifecycles: Manages activity and fragment lifecycles of the app, changes survive configuration, avoids memory leaks, and quickly loads data into the UI. 
  • Live Data: Notifies views of any database modifications and also used to build data objects that notify the views.

Code 1 Live Data


Here, in the project there gets a list of habits and the list with LiveData is wrapping

Google Code Labs

  • Navigation: Handles everything that required for in-app navigation in Android application.
  • Paging: Helps in loading data on demand from the data source.
  • Room: It is an SQLite object mapping library used to avoid boilerplate code and easily convert SQLite table data to Java objects. A Room provides compile-time checks of SQLite statements and can return RXJava, Flowable, and LiveData observables.
  • ViewModel: Manages UI-related data in a lifecycle conscious way and stores UI-related data that is not destroyed on app rotations. This will help to provide data between repository and UI, which remains the data on configuration changes and receives the existing ViewModel to reconnect with the new occurrence of the owner. 

This is the lifecycle of ViewModel attached to an activity. Activity created and stopped many times, but ViewModel remains the data. ViewModel is not the replacement of onSaveInsatnce because does not survive process shutdown although onSaveInstance can restore small data and ViewModel can restore a large amount of data like bitmaps.

HabitViewModel.kt

 Using AndroidViewModel because there is a need for an application context. Creating insert wrapper which will use the repository’s insert method.

  • Workmanager: Manages every background jobs in Android with the circumstances that are chosen.

Requirements for creating Room Database

  • Add Dependencies:

    For this, one needs to add Room and lifecycle components. Lifecycle has a good set of classes like ViewModel and LiveData, which will use to manage the lifecycle of our app. Add these libraries to build.gradle file, at the end of the dependencies section.

Add Dependencies

  • Setup Room: There are three significant annotations for using room: 
    • “@Entity”
    • “@Dao”
    • “@Database”
      • @Entity:

        Table and columns representation becomes very easy; here have to annotate “ @Entity” to class, and the name of the class becomes the name of the columns. “@Entity” class represent an entity in a table.

Entity

In the above example, the class Habit represents the habitClass table, with a single column named “habit”. The @ColumnInfo annotation specifies details about the column, and it also annotates “@PrimaryKey” to make it a primary key.

      • @Dao:

        Data Access Object is an interface where all the SQL queries are placed. Here, there is no need to write the whole queries, need to make a method and annotate with specific annotations like “@insert,” “@Delete,” “@Query(SELECT FROM*)”

DAO

In the above example, the interface used is HabitDao, which contains methods used to perform queries. To insert the data annotated with “@insert” to insert method. “@Query” to do some custom queries. A Room doesn’t give annotations, which can help in deleting everything.

      • @Database:

        For this, one should create an abstract class(Room class) that extends the RoomDatabase. It is a database layer over the SQLite database that supports in all works which are similar to SQLiteOpenHelper class. Room facilitates compile-time checking of SQL statements and requires only a single instance for the whole app.

Database

In the above code example, there’s a Room class called HabitRoomDatabase used to declare all entities and the database version. The getDatabase() method returns the Room database instance. Migration is employed to modify the database.

  • Create the Repository Class:

    A repository reconciles between the domain and data mapping layers, by acting like an in-memory domain object collection. Where one can access the database class and the DAO class from the repository and perform a list of operations such as insert, update, delete, get.

Repository

  • RecyclerView: Creates a layout file, TextView in a row and also create a file which consists of RecyclerView.  Need an adapter class which is responsible for showing data on the screen.

RecyclerView

In the above example, if the list is empty, then display a proper message to the user.

  • Filling the Database:

    Here, the data gets populated whenever the app starts and before that deleted the existing data. There is a PopulateDbAsync which is an AsyncTask use to delete and insert the data.

FillingDatabase

  • Connect UI and Data:

    Which is used to display the data from the database, the observer will be needed to observe the data changes, LiveData in the ViewModel. The ViewModel providesViewModelProvider is going to create a ViewModel. Connect the ViewModel with the ViewModelProvider, and then in the onChanged method, retrieve updated data for display on the screen.

Connect UI and Data

In the above code, MainActivity contains a fab button that opens another activity for entering data. By creating the onActivityResult method which gives the data that the user had entered and inserted into the database.

  • Second Activity:

    Where the user can input the data need for the activity. The EditText Button is used to submit the string.

Second Activity

Tips for Room Database creation

Now let’s look at some of the tips for Room 

Room is an abstraction layer on the top of SQLite that makes it easier and friendlier to persist data. If you’re new to Room then check out some pro-tips on getting the most out of the Room:

  • Pre-populate your database via RoomDatabase#Callback
  • Use DAO’s inheritance capability
  • Execute queries in transactions with minimal boilerplate code via@Transaction
  • Read only what you need
  • Enforce constraints between entities with foreign keys
  • Simplify one-to-many queries via @Relation
  • Avoid false positive notifications for observable queries
To Conclude

There are a lot of steps to use the Architecture components and execute the recommended architecture. The most important thing is to build a model of what is running on and know how the parts fit together and how the data flows.

Krify is one among the top and best mobile app development company in India and the UK. The mobile app developers having well experienced and skilled knowledge of all the emerging technologies. Looking for the website or mobile app development for your business. Contact us for your idea to come real at your budget.  

Scroll to Top