Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Java Edition

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

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815161
Pages 810 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (88) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Overview of Android View Binding 12. Understanding Android Application and Activity Lifecycles 13. Handling Android Activity State Changes 14. Android Activity State Changes by Example 15. Saving and Restoring the State of an Android Activity 16. Understanding Android Views, View Groups and Layouts 17. A Guide to the Android Studio Layout Editor Tool 18. A Guide to the Android ConstraintLayout 19. A Guide to using ConstraintLayout in Android Studio 20. Working with ConstraintLayout Chains and Ratios in Android Studio 21. An Android Studio Layout Editor ConstraintLayout Tutorial 22. Manual XML Layout Design in Android Studio 23. Managing Constraints using Constraint Sets 24. An Android ConstraintSet Tutorial 25. A Guide to using Apply Changes in Android Studio 26. An Overview and Example of Android Event Handling 27. Android Touch and Multi-touch Event Handling 28. Detecting Common Gestures using the Android Gesture Detector Class 29. Implementing Custom Gesture and Pinch Recognition on Android 30. An Introduction to Android Fragments 31. Using Fragments in Android Studio - An Example 32. Modern Android App Architecture with Jetpack 33. An Android Jetpack ViewModel Tutorial 34. An Android Jetpack LiveData Tutorial 35. An Overview of Android Jetpack Data Binding 36. An Android Jetpack Data Binding Tutorial 37. An Android ViewModel Saved State Tutorial 38. Working with Android Lifecycle-Aware Components 39. An Android Jetpack Lifecycle Awareness Tutorial 40. An Overview of the Navigation Architecture Component 41. An Android Jetpack Navigation Component Tutorial 42. Creating and Managing Overflow Menus on Android 43. An Introduction to MotionLayout 44. An Android MotionLayout Editor Tutorial 45. A MotionLayout KeyCycle Tutorial 46. Working with the Floating Action Button and Snackbar 47. Creating a Tabbed Interface using the TabLayout Component 48. Working with the RecyclerView and CardView Widgets 49. An Android RecyclerView and CardView Tutorial 50. A Layout Editor Sample Data Tutorial 51. Working with the AppBar and Collapsing Toolbar Layouts 52. An Android Studio Master/Detail Flow Tutorial 53. An Overview of Android Intents 54. Android Explicit Intents – A Worked Example 55. Android Implicit Intents – A Worked Example 56. Android Broadcast Intents and Broadcast Receivers 57. A Basic Overview of Threads and AsyncTasks 58. An Overview of Android Started and Bound Services 59. Implementing an Android Started Service – A Worked Example 60. Android Local Bound Services – A Worked Example 61. Android Remote Bound Services – A Worked Example 62. An Android Notifications Tutorial 63. An Android Direct Reply Notification Tutorial 64. Foldable Devices and Multi-Window Support 65. An Overview of Android SQLite Databases 66. The Android Room Persistence Library 67. An Android TableLayout and TableRow Tutorial 68. An Android Room Database and Repository Tutorial 69. Accessing Cloud Storage using the Android Storage Access Framework 70. An Android Storage Access Framework Example 71. Video Playback on Android using the VideoView and MediaController Classes 72. Android Picture-in-Picture Mode 73. An Android Picture-in-Picture Tutorial 74. Making Runtime Permission Requests in Android 75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 76. Working with the Google Maps Android API in Android Studio 77. Printing with the Android Printing Framework 78. An Android HTML and Web Content Printing Example 79. A Guide to Android Custom Document Printing 80. An Introduction to Android App Links 81. An Android Studio App Links Tutorial 82. A Guide to the Android Studio Profiler 83. An Android Biometric Authentication Tutorial 84. Creating, Testing and Uploading an Android App Bundle 85. An Overview of Android Dynamic Feature Modules 86. An Android Studio Dynamic Feature Tutorial 87. An Overview of Gradle in Android Studio Index

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 2021 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}