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.2 Development Essentials - Kotlin Edition

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

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

Table of Contents (94) 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 Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to Using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures Using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Primary/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. An Introduction to Kotlin Coroutines 64. An Android Kotlin Coroutines Tutorial 65. An Overview of Android Services 66. Implementing an Android Started Service – A Worked Example 67. Android Local Bound Services – A Worked Example 68. Android Remote Bound Services – A Worked Example 69. An Android Notifications Tutorial 70. An Android Direct Reply Notification Tutorial 71. Foldable Devices and Multi-Window Support 72. An Overview of Android SQLite Databases 73. The Android Room Persistence Library 74. An Android TableLayout and TableRow Tutorial 75. An Android Room Database and Repository Tutorial 76. Accessing Cloud Storage using the Android Storage Access Framework 77. An Android Storage Access Framework Example 78. Video Playback on Android using the VideoView and MediaController Classes 79. Android Picture-in-Picture Mode 80. An Android Picture-in-Picture Tutorial 81. Making Runtime Permission Requests in Android 82. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 83. Printing with the Android Printing Framework 84. An Android HTML and Web Content Printing Example 85. A Guide to Android Custom Document Printing 86. An Introduction to Android App Links 87. An Android Studio App Links Tutorial 88. A Guide to the Android Studio Profiler 89. An Android Biometric Authentication Tutorial 90. Creating, Testing and Uploading an Android App Bundle 91. An Overview of Android Dynamic Feature Modules 92. An Android Studio Dynamic Feature Tutorial 93. An Overview of Gradle in Android Studio Index

73. 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.

73.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 73-1 outlines the recommended architecture for a typical Android app:

Figure 73-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.

73.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:

73.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.

73.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.

73.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...

73.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 Kotlin class interspersed with some special Room annotations. An example Kotlin class declaring the data to be stored within a database table might read as follows:

class Customer {

 

    var id: Int = 0

    var name: String? = null

    var address: String? = null

 

    constructor() {}

 

    constructor(id: Int, name: String, address: String) {

        this.id = id

        this.name = name

        this.address = address

    }

    constructor(name: String, address: String) {

    ...

73.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 Kotlin 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

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

interface CustomerDao {

   @Query("SELECT * FROM customers")

   fun getAllCustomers(): LiveData<List<Customer>>

}

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

73.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)

abstract...

73.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:

class CustomerRepository(application: Application) {

 

    private var customerDao: CustomerDao?

    

    init {

        val db: CustomerRoomDatabase? =

                   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...

73.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<CustomerRoomDatabase>(context.applicationContext,

        CustomerRoomDatabase::class.java, "customer_database")

   ...

73.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 73-3:

Figure 73-3

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

73.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.2 Development Essentials - Kotlin Edition
Published in: Aug 2021 Publisher: Packt ISBN-13: 9781803231549
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 £13.99/month. Cancel anytime}