Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
How to Build Android Apps with Kotlin

You're reading from  How to Build Android Apps with Kotlin

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781838984113
Pages 794 pages
Edition 1st Edition
Languages
Authors (4):
Alex Forrester Alex Forrester
Profile icon Alex Forrester
Eran Boudjnah Eran Boudjnah
Profile icon Eran Boudjnah
Alexandru Dumbravan Alexandru Dumbravan
Profile icon Alexandru Dumbravan
Jomar Tigcal Jomar Tigcal
Profile icon Jomar Tigcal
View More author details

Table of Contents (17) Chapters

Preface
1. Creating Your First App 2. Building User Screen Flows 3. Developing the UI with Fragments 4. Building App Navigation 5. Essential Libraries: Retrofit, Moshi, and Glide 6. RecyclerView 7. Android Permissions and Google Maps 8. Services, WorkManager, and Notifications 9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso 10. Android Architecture Components 11. Persisting Data 12. Dependency Injection with Dagger and Koin 13. RxJava and Coroutines 14. Architecture Patterns 15. Animations and Transitions with CoordinatorLayout and MotionLayout 16. Launching Your App on Google Play

11. Persisting Data

Overview

This chapter goes in depth about data persistence in Android, as well as exploring the repository pattern. By the end of the chapter, you will be able to build a repository that can connect to multiple data sources, and then use this repository to download files from an API and save them on a device. You will know multiple ways to store (persist) data directly on a device and the frameworks accessible to do this. When dealing with a filesystem, you will learn how it's partitioned and how you can read and write files in different locations and using different frameworks.

Introduction

In the previous chapter, you learned how to structure your code and how to save data. In the activity, you also had the opportunity to build a repository and use it to access data and save data through Room. You probably asked the question: Why do you need this repository? This chapter will seek to answer that. With the repository pattern, you will be able to retrieve data from a server and store it locally in a centralized way. The pattern is useful in situations where the same data is required in multiple places, thereby avoiding code duplication while also keeping ViewModels clean of any unnecessary extra logic.

If you look into the Settings app on your device, or the Settings feature of many apps, you will see some similarities. A list of items with toggles that can be on or off. This is achieved through SharedPreferences and PreferenceFragments. SharedPreferences is a way that allows you to store values in a file in key-value pairs. It has specialized mechanisms...

Repository

Repository is a pattern that helps developers keep code for data sources separate from activities and ViewModels. It offers centralized access to data that can then be unit tested:

Figure 11.1: Diagram of repository architecture

In the preceding diagram, you can see the central role the repository plays in an application's code. Its responsibilities include:

  • Keeping all the data sources (SQLite, Network, File System) required by your activity or the application
  • Combining and transforming the data from multiple sources into a single output required at your activity level
  • Transferring data from one data source to another (saving the result of a network call to Room)
  • Refreshing expired data (if necessary)

Room, network layer, and FileManager represent the different types of data sources your repository can have. Room may be used to save large amounts of data from the network, while the filesystem can be used to store...

Preferences

Imagine you are tasked with integrating a third-party API that uses something such as OAuth to implement logging in with Facebook, Google, and suchlike. The way these mechanisms work is as follows: they give you a token that you have to store locally and that can then be used to send other requests to access user data. The questions you're faced with are: How can you store that token? Do you use Room just for one token? Do you save the token in a separate file and implement methods for writing the file? What if that file has to be accessed in multiple places at the same time? SharedPreferences is an answer to these questions. SharedPreferences is a functionality that allows you to save Booleans, integers, floats, longs, strings, and sets of strings into an XML file. When you want to save new values, you specify what values you want to save for the associated keys, and when you are done, you commit the change, which will trigger the save to the XML file in an asynchronous...

Files

We've discussed Room and SharedPreferences and specified how the data they store is written to files. You may ask yourself, where are these files stored? These particular files are stored in internal storage. Internal storage is a dedicated space for every app that other apps are unable to access (unless the device is rooted). There is no limit to the amount of storage your app uses. However, users have the ability to delete your app's files from the Settings menu. Internal storage occupies a smaller part of the total available space, which means that you should be careful when it comes to storing files in internal storage. There is also external storage. The files your app stores are accessible to other apps and the files from other apps are accessible to your app:

Note

In Android Studio, you can use the Device File Explorer tool to navigate through the files on the device or emulator. Internal storage is located in /data/data/{packageName}. If you have access...

Scoped Storage

Since Android 10 and with further updates in Android 11, the notion of Scoped Storage was introduced. The main idea behind this is to allow apps to gain more control of their files on the external storage and prevent other apps from accessing these files. The consequences of this mean that READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE will only apply for files the user interacts with (like media files). This discourages apps to create their own directories on the external storage and instead stick with the one already provided to them through the Context.getExternalFilesDir.

FileProviders and Storage Access Framework are a good way of keeping your app's compliance with the scoped storage practices because one allows the app to use the Context.getExternalFilesDir and the other uses the built-in File Explorer app which will now avoid files from other applications in the Android/data and Android/obb folders on the external storage.

Camera and Media Storage...

Summary

In this chapter, we've analyzed the different ways of persisting data in Android and how to centralize them through the repository pattern. We've started with a look at the pattern itself to see how we can organize the data sources by combining Room and Retrofit.

Then, we moved on to analyze alternatives to Room when it comes to persisting data. We looked first at SharedPreferences and how they constitute a handy solution for data persistence when it's in a key-value format and the amount of data is small. We then looked at how you can use SharedPreferences to save data directly on the device, and then we examined PreferenceFragments and how they can be used to take in user input and store it locally.

Next, we looked over something that was in continuous change when it comes to the Android framework. That is the evolution of the abstractions regarding the filesystem. We started with an overview of the types of storage Android has and then took a more in...

lock icon The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021 Publisher: Packt ISBN-13: 9781838984113
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 $15.99/month. Cancel anytime}