Reader small image

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

Product typeBook
Published inMay 2023
PublisherPackt
ISBN-139781837634934
Edition2nd Edition
Right arrow
Authors (4):
Alex Forrester
Alex Forrester
author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

Eran Boudjnah
Eran Boudjnah
author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

Alexandru Dumbravan
Alexandru Dumbravan
author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

Jomar Tigcal
Jomar Tigcal
author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal

View More author details
Right arrow

Essential Libraries: Retrofit, Moshi, and Glide

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 ImageView using Glide.

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.

We will cover the following topics in this chapter:

  • Introducing REST, API, JSON, and XML
  • Fetching data from a network endpoint
  • Parsing a JSON response
  • Loading images from a remote URL

Technical requirements

The complete code for all the exercises and the activity in this chapter is available on GitHub at https://packt.link/Uqtjm

Introducing REST, API, JSON, and XML

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

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

Note

To read more about REST, visit https://packt.link/YsSRV.

When applied to a web service application programming interface (API), we get a Hypertext Transfer Protocol (HTTP)-based...

Fetching data from a network endpoint

For the purpose of this section, we will use The Cat API (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, which 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 the 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 must 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 (see https://github.com/google/gson) and, more recently, Square’s Moshi (see 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 ...

Loading images from a remote URL

We just learned how to extract data from an API response. That data often includes URLs to images we want to present to the user. There is quite a bit of work involved in achieving that. First, you must 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 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 (see https://square.github.io/picasso/) and Glide by Bump Technologies (see https://github.com/bumptech/glide). Facebook’s Fresco (see https://frescolib.org/) is somewhat less...

Summary

In this chapter, we learned how to fetch data from an API using Retrofit. We then learned how to handle JSON responses, as well as plain text responses, using Moshi. We also saw how different error scenarios could 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 and 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 purposes 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 - Second Edition
Published in: May 2023Publisher: PacktISBN-13: 9781837634934
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 $15.99/month. Cancel anytime

Authors (4)

author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal