Android provides several options to save data locally on the device. Today, we will look at 2 of the most common methods.

Shared preferences: Store primitive data in key-value pairs. This is used for e.g. storing the data of a settings menu.

Room persistence library: An Object-Relational Mapper (ORM), that is used to store large amounts of structured and related data in an SQL database using SQLite.

What you'll learn

Create an app with a TextView, EditText and Button. Clicking the Button should display the value of the EditText in the TextView. The data data inside the TextView must persist if the application is closed.

In the following exercises we are going to create an application, that stores large amounts of structured data in an SQLite database.

  1. Come up with an idea for your app - what are you going to store? Pets, Pokemon, Movies?
  2. Create an interface, that allows to create, read and delete all data in your database
  3. Utilize MVVM and the Repository pattern

We will use the Room persistence library to create and manage the SQLite database. Include the dependencies to the library in your project.

Create an Entity of the data you are going to save.

Create a DAO, that should allow for inserting, deleting and reading from the SQLite database. For reading, let the DAO return LiveData.

Create the Room Database Object, that holds the SQLite database.

Now that Room is set up, we can use it in our Repository.

Make sure your View, ViewModel and Repository has the proper CRUD methods.

To get the instance of the database, Context needs to be passed as an argument. The Repository does not know about Context, therefore:

Let the ViewModel provide Context to the Repository

Use ExecutorService to interact with the methods of the DAO on a background thread.

You should now have a working application, that can insert and delete data to/from your database, with the changes instantly visible using LiveData. Try to add new functionality using annotations or custom SQL-queries. For example: Updating existing data, sorting or searching for specific data.

Create a settings menu for your application, that stores some user preferences.