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

5. Essential Libraries: Retrofit, Moshi, and Glide

Overview

In this chapter, we will cover the steps needed to present app users with dynamic content fetched from remote servers. You will be introduced to the different libraries required to retrieve and handle this dynamic data.

By the end of this chapter, you will be able to fetch data from a network endpoint using Retrofit, parse JSON payloads into Kotlin data objects using Moshi, and load images into ImageViews using Glide.

Introduction

In the previous chapter, we learned how to implement navigation in our app. In this chapter, we will learn how to present dynamic content to the user as they navigate around our app.

Data presented to users can come from different sources. It can be hardcoded into the app, but that comes with limitations. To change hardcoded data, we have to publish an update to our app. Some data cannot be hardcoded by its nature, such as currency exchange rates, the real-time availability of assets, and the current weather, to name a few. Other data may become outdated, such as the terms of use of an app.

In such cases, you would usually fetch the relevant data from a server. One of the most common architectures for serving such data is the representational state transfer (REST) architecture. The REST architecture is defined by a set of six constraints: the client-server architecture, statelessness, cacheability, a layered system, code on demand (optional), and a uniform interface...

Fetching Data from a Network Endpoint

For the purpose of this section, we will use TheCatAPI (https://thecatapi.com/). This RESTful API offers us vast data about, well… cats.

To get started, we will create a new project. We then have to grant our app internet access permission. This is done by adding the following code to your AndroidManifest.xml file, right before the Application tag:

    <uses-permission android:name="android.permission.INTERNET" />

Next, we need to set up our app to include Retrofit. Retrofit is a type-safe library provided by Square that is built on top of the OkHttp HTTP client. Retrofit helps us generate Uniform Resource Locators (URLs), which are the addresses of the server endpoints we want to access. It also makes the decoding of JSON payloads easier by providing integration with several parsing libraries. Sending data to the server is also easier with Retrofit, as it helps with encoding the requests...

Parsing a JSON Response

Now that we have successfully retrieved a JSON response from an API, it is time to learn how to use the data we have obtained. To do so, we need to parse the JSON payload. This is because the payload is a plain string representing the data object, and we are interested in specific properties of that object. If you look closely at Figure 5.2, you may notice that the JSON contains breed information, an image URL, and some other bits of information. However, for our code to use that information, first we have to extract it.

As mentioned in the introduction, multiple libraries exist that will parse a JSON payload for us. The most popular ones are Google's GSON (https://github.com/google/gson) and, more recently, Square's Moshi (https://github.com/square/moshi). Moshi is very lightweight, which is why we have chosen to use it in this chapter.

What do JSON libraries do? Basically, they help us convert data classes into JSON strings (serialization)...

Loading Images from a Remote URL

We just learned how to extract particular data from an API response. Quite often, that data will include URLs to images we want to present to the user. There is quite a bit of work involved in achieving that. First, you have to fetch the image as a binary stream from the URL. Then, you need to transform that binary stream into an image (it could be a GIF, JPEG, or one of a few other image formats). Then, you need to convert it into a bitmap instance, potentially resizing it to use less memory.

You may also want to apply other transformations to it at that point. Then, you need to set it to an ImageView. Sounds like a lot of work, doesn't it? Well, luckily for us, there are a few libraries that do all of that (and more) for us. The most commonly used libraries are Square's Picasso (https://square.github.io/picasso/) and Glide by Bump Technologies (https://github.com/bumptech/glide). Facebook's Fresco (https://frescolib.org/) is somewhat...

Summary

In this chapter, we learned how to fetch data from an API using Retrofit. We then learned how to handle JSON responses using Moshi, as well as plain text responses. We also saw how different error scenarios can be handled.

We later learned how to load images from URLs using Glide and how to present them to the user via ImageView.

There are quite a few popular libraries for fetching data from APIs as well as for loading images. We only covered some of the most popular ones. You might want to try out some of the other libraries to find out which ones fit your purpose best.

In the next chapter, we will be introduced to RecyclerView, which is a powerful UI component that we can use to present our users with lists of items.

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 £13.99/month. Cancel anytime}