Save Data on Android Using Room Database and Data Store— Beginners Guide

Inuwa Ibrahim
ProAndroidDev
Published in
5 min readJun 2, 2021

--

If you have been looking for ways of storing data without having to deal with an online storage/database on android, welcome..

In Android, there are 2 ways of providing offline storage of data:
1. Room Database
2. Preferences (SharedPreference and Preference DataStore).

Now, what are the differences?. When should you use Room Databaseand when should you use Preferences

Do you want to store just a small amount of data — Preferences
Use Case

— Storing a users selection for night mode or dark mode on your app
— Saving the state when a user first launches your app (Useful for displaying one time intro screen)
— Storing a users sort order for a list of items (So when the user comes back to the list, the sort order is retained)

Do you want to store large amount of data — Room
Use Case
— Saving a list of songs a user has marked as favourite (In this case a table is needed with columns)
— Storing a list of posts (Probably with text and images), so when a user isn’t connected, he gets to view somethings from the room database, this is the technique used in most social media apps like instagram.

Now you know when to use both.
This article focuses on Room Database and DataStore

LETS GET CODING….

For this tutorial, we will be building a simple app that stores user information (Name, age and phone number) in Room Database and persist screen with Data Store

Here is what our final app will look like

First Screen for saving user info to room database

After filling your info and clicking SAVE, this is the next screen

User details screen gotten from room

Here is a video showing how it works:

STEPS

NOTE:- The Architecture used for this project is MVVM (Model View ViewModel)

  • ADD DEPENDENCIES
  • SET UP ROOM DATABASE
  • SET UP PREFERENCES (DataStore)
  • SET UP HILT (For Dependency Injection)
  • SET UP REPOSITORY
  • SET UP VIEWMODEL
  • SET UP VIEW

ADD DEPENDENCIES

  • Open Build.gradle file and add the necessary dependencies
  • Check — Build.gradle(Project) and Build.gradle(App) for all dependencies used — Check here
  • Some of the dependencies used are:
    Coroutines — For Asynchronous Operations
    Hilt — For Dependency Injection
    Preference DataStore — For consistent asynchronous data storage
    Room — For offline data storage
    ViewBinding — For Interacting with views
    LiveData, ViewModel and LifeCycle Dependencies

SET UP ROOM DATABASE

  • Create a new package → database
  • Create a new kotlin file → UserDatabase.kt
UserDatabase.kt

— This class is annotated with @Database to signify that this is a room database which consist of User class entity [Table]. The version number is used to signify update/change in room database. When there is a change in your model or table, this number should be increased

UserDao (User Data Access Object) class is used to signify operations that need to be carried out for our UsersTable e.g CRUD operations (We will create this class soon)

Callback will be used to provide dependency using Hilt

  • Create another class → User.kt
User.kt

— This class is used as a model, which represents a table in our database as Annotated with @Entity

  • Create an interface — UserDao.kt
UserDao.kt

— This class contains all operations that can be performed on our object.
In this tutorial, we made use of just 2 operations:
Create - For inserting records in the database
Delete - For Deleting record in the database.
You can make use of any of the operations in that class

SET UP PREFERENCES (DATASTORE)

We are making use of preference to make sure the activity screen (Used for filling user information) is only shown when a user has no records in the database. We will show the user details activity screen instead.

So we will basically set up a boolean to check if user has saved his details in room → then show appropriate screen/activity.

  • Under Preference Package, create an interface called PreferenceStorage.kt

— This interface consist of 2 functions:
1. savedKey() For getting saved key (Boolean), used to check if the preference has been saved or not
2. setSavedKey() For setting a value to the preference (Either true/false)

— Create a new file → PreferenceImpl.kt

— This class contains overridden methods which contains codes for Asynchronous data storage and retrieval using Kotlin Flows

SET UP HILT — FOR DEPENDENCY INJECTION

In order to avoid complexities, this tutorial focuses more on Room Database Integration. To see how Hilt was integrated with this project, check full source code. [Global package]

SET UP REPOSITORY

  • Under Repo package, create a new file → UserRepo.kt
UserRepo.kt

— This class uses coroutines to perform the necessary database operations in the background thread. Functions are self explanatory

SET UP VIEWMODEL

— Under ViewModel package, create a new kotlin class → UserViewModel.kt

  • Again, using kotlin couroutines and a combination of LiveData Or StateFlow we subscribe for live updates to operations which can be observed in the View (UI)

— Create another new class → DataStoreViewModel.kt

  • This class consists of codes used to “subscribe” for updates when preference changes which is then observed in our view -> This is the benefit of using DataStore over SharedPreference as data is stored asynchronously, consistently, and transactionally.

SET UP VIEW

  • The project consists of 2 activities:
    MainActivity
    UserDetailsActivity

— Check resource directory in full source code for both layout: activity_main.xml and activity_user_details.xml

MainActivity

MainActivity.kt
  • The codes for MainActivity is self explanatory.
    First → We check if preferences exist. If it exists, navigate to UserDetails Activity screen — checkIfUserHasSavedDetails()
  • We made the button not clickable when any of the fields is empty to avoid sending empty entries into room database — Using a textWatcher makeButtonNotClickableAtFirst()
  • On click ‘Save’ button, we save the user details to room database and update our preferences (data storage) by setting its boolean value to ‘True’, Then we send an Intent to UserDetailsActivity Screen.

UserDetailsActivity

UserDetailsActivity

— In here we get user details and set to the appropriate views.
— On click ‘Clear Record’, The user record is removed/deleted from both Room Database and Preference Datastore respectively.

That’ll be all for this tutorial. 😺

Link to full code
https://github.com/ibrajix/RoomDatabase

Contact me
https://linktr.ee/Ibrajix

--

--