Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

66. The Android Room Persistence Library

Included with the Android Architecture Components, the Room persistence library is designed specifically to make it easier to add database storage support to Android apps in a way that is consistent with the Android architecture guidelines. With the basics of SQLite databases covered in the previous chapter, this chapter will explore the basic concepts behind Room-based database management, the key elements that work together to implement Room support within an Android app and how these are implemented in terms of architecture and coding. Having covered these topics, the next two chapters will put this theory into practice in the form of an example Room database project.

66.1 Revisiting Modern App Architecture

The chapter entitled “Modern Android App Architecture with Jetpack” introduced the concept of modern app architecture and stressed the importance of separating different areas of responsibility within an app. The diagram illustrated in Figure 66-1 outlines the recommended architecture for a typical Android app:

Figure 66-1

With the top three levels of this architecture covered in some detail in earlier chapters of this book, it is now time to begin exploration of the repository and database architecture levels in the context of the Room persistence library.

66.2 Key Elements of Room Database Persistence

Before going into greater detail later in the chapter, it is first worth summarizing the key elements involved in working with SQLite databases using the Room persistence library:

66.2.1 Repository

As previously discussed, the repository module contains all of the code necessary for directly handling all data sources used by the app. This avoids the need for the UI controller and ViewModel to contain code that directly accesses sources such as databases or web services.

66.2.2 Room Database

The room database object provides the interface to the underlying SQLite database. It also provides the repository with access to the Data Access Object (DAO). An app should only have one room database instance which may then be used to access multiple database tables.

66.2.3 Data Access Object (DAO)

The DAO contains the SQL statements required by the repository to insert, retrieve and delete data within the SQLite database. These...

66.3 Understanding Entities

Each database table will have associated with it an entity class. This class defines the schema for the table and takes the form of a standard Java class interspersed with some special Room annotations. An example Java class declaring the data to be stored within a database table might read as follows:

public class Customer {

 

    private int id;

    private String name;

    private string address;

 

    public Customer(String name, String address) {

        this.id = id;

        this.name = name;

        this.address = address;

    }

 

    public int getId() {

        return this.id;

    }

 ...

66.4 Data Access Objects

A Data Access Object provides a way to access the data stored within a SQLite database. A DAO is declared as a standard Java interface with some additional annotations that map specific SQL statements to methods that may then be called by the repository.

The first step is to create the interface and declare it as a DAO using the @Dao annotation:

@Dao

public interface CustomerDao {

}

Next, entries are added consisting of SQL statements and corresponding method names. The following declaration, for example, allows all of the rows in the customers table to be retrieved via a call to a method named getAllCustomers():

@Dao

public interface CustomerDao {

    @Query("SELECT * FROM customers")

    LiveData<List<Customer>> getAllCustomers();

}

Note that the getAllCustomers() method returns a List object containing a Customer entity object for each record retrieved from the...

66.5 The Room Database

The Room database class is created by extending the RoomDatabase class and acts as a layer on top of the actual SQLite database embedded into the Android operating system. The class is responsible for creating and returning a new room database instance and for providing access to the DAO instances associated with the database.

The Room persistence library provides a database builder for creating database instances. Each Android app should only have one room database instance, so it is best to implement defensive code within the class to prevent more than one instance being created.

An example Room Database implementation for use with the example customer table is outlined in the following code listing:

import android.content.Context;

import android.arch.persistence.room.Database;

import android.arch.persistence.room.Room;

import android.arch.persistence.room.RoomDatabase;

 

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

public...

66.6 The Repository

The repository is responsible for getting a Room Database instance, using that instance to access associated DAOs and then making calls to DAO methods to perform database operations. A typical constructor for a repository designed to work with a Room Database might read as follows:

public class CustomerRepository {

 

    private CustomerDao customerDao;

    private CustomerRoomDatabase db;

 

    public CustomerRepository(Application application) {

        db = CustomerRoomDatabase.getDatabase(application);

        customerDao = db.customerDao();

    }

.

.

}

Once the repository has access to the DAO, it can make calls to the data access methods. The following code, for example, calls the getAllCustomers() DAO method:

private LiveData<List<Customer>...

66.7 In-Memory Databases

The examples outlined in this chapter involved the use of a SQLite database that exists as a database file on the persistent storage of an Android device. This ensures that the data persists even after the app process is terminated.

The Room database persistence library also supports in-memory databases. These databases reside entirely in memory and are lost when the app terminates. The only change necessary to work with an in-memory database is to call the Room.inMemoryDatabaseBuilder() method of the Room Database class instead of Room.databaseBuilder(). The following code shows the difference between the method calls (note that the in-memory database does not require a database name):

// Create a file storage based database

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),

                          &...

66.8 Database Inspector

Android Studio includes a Database Inspector tool window which allows the Room databases associated with running apps to be viewed, searched and modified as shown in Figure 66-3:

Figure 66-3

Use of the Database Inspector will be covered in the chapter entitled “An Android Room Database and Repository Tutorial”.

66.9 Summary

The Android Room persistence library is bundled with the Android Architecture Components and acts as an abstract layer above the lower level SQLite database. The library is designed to make it easier to work with databases while conforming to the Android architecture guidelines. This chapter has introduced the different elements that interact to build Room-based database storage into Android app projects including entities, repositories, data access objects, annotations and Room Database instances.

With the basics of SQLite and the Room architecture component covered, the next step is to create an example app that puts this theory into practice. Since the user interface for the example application will require a forms based layout, the next chapter, entitled “An Android TableLayout and TableRow Tutorial”, will detour slightly from the core topic by introducing the basics of the TableLayout and TableRow views.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth