Search⌘ K
AI Features

Handling Internet Connections

Understand how to implement internet connection handling in your Android apps by extending AndroidViewModel. Learn to detect network status, manage API calls safely, and display user-friendly error messages. This lesson guides you through refactoring ViewModel code to integrate connectivity checks and improve app reliability.

Why handle internet connections?

Most Android applications fetch data remotely from APIs, and to do that efficiently, our device needs to be connected to an active network.

We, as developers, must inform the user when an internet connection is required to load data. To do that, we must develop a mechanism to simply detect if the device is connected to an active internet connection source.This can be mobile data or a WiFi connection.

In other instances, an application can just crash if it’s meant to make use of the internet and the device is not connected. This is a case where the developer hasn’t handled internet connection issues. In this lesson, we’ll learn how to handle internet connections in our Android programs.

Making changes to the ViewModel

Views are only used to present data. UI-related logic is handled by the ViewModel. We’ll make a few changes to the NewsViewModel to accommodate the logic that handles internet connectivity. Let’s get into it!

Instead of NewsViewModel extending the ViewModel class, we’ll extend the AndroidViewModel. The difference ...