Fetching and Storing Data in Android Apps

Tutorial 5 of 5

1. Introduction

This tutorial will teach you how to fetch and store data in your Android applications. We will discuss different storage options, and you will learn how to interact with APIs to fetch data from the internet. We'll also cover best practices and provide practical examples to guide you.

At the end of this tutorial, you'll be able to:
- Understand the different data storage options in Android
- Fetch data from the web using APIs
- Store and retrieve data in Android apps

Prerequisites: Basic understanding of Android development and Java or Kotlin programming languages.

2. Step-by-Step Guide

Android Storage Options

There are several options for data storage in Android:

  • Shared Preferences: Stores data as key-value pairs. It's ideal for storing small amounts of data like settings.
  • Internal Storage: Stores data in the device's memory. This data is private to your application.
  • External Storage: Stores data on the device's external memory like an SD card. The data is public and can be accessed by other apps.
  • SQLite Databases: Allows you to store structured data in a private database.
  • Network Connection: Fetch data from the web via APIs.

We'll focus on Shared Preferences and fetching data from the web in this tutorial.

Fetching Data from the Web

Fetching data from the web involves sending a request to a server and receiving a response. Android uses HttpURLConnection or libraries like Retrofit and Volley for network operations.

3. Code Examples

Storing Data with Shared Preferences

Here's a simple example of how to store and retrieve data using Shared Preferences in Kotlin.

// Access the shared preferences
val sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)

// Write to shared preferences
val editor = sharedPref.edit()
editor.putString("username", "John Doe")
editor.apply()

// Read from shared preferences
val username = sharedPref.getString("username", "defaultName")

In this code:
- We first access the shared preferences file named "myPrefs".
- We then get an instance of SharedPreferences.Editor to write to the preferences.
- We call putString to store a string and then apply to save the changes.
- To read from the preferences, we call getString, passing in the key and a default value.

Fetching Data with HttpURLConnection

Here's an example of how to fetch data from a web API using HttpURLConnection.

val url = URL("https://api.example.com/data")

with(url.openConnection() as HttpURLConnection) {
    requestMethod = "GET"  // optional default is GET

    println("Response Code: $responseCode")

    inputStream.bufferedReader().use {
        it.lines().collect(Collectors.joining("\n"))
    }
}

In this code:
- We create a URL object with the API URL.
- We open a connection and cast it to HttpURLConnection.
- We set the request method to "GET".
- We print the response code.
- We read the response using a BufferedReader.

4. Summary

In this tutorial, you've learned about different data storage options in Android. You've also learned how to fetch data from the web using HttpURLConnection and how to store and retrieve data using Shared Preferences.

For further learning, consider exploring other storage options like SQLite databases and external storage. Also, consider learning about libraries like Retrofit and Volley for easier network operations.

5. Practice Exercises

  1. Create an app that stores and retrieves a user's favorite color using Shared Preferences.
  2. Fetch data from this API: https://jsonplaceholder.typicode.com/posts. Print the data in the console.

Solutions:

  1. Here's a solution for the first exercise:
// Store favorite color
val editor = sharedPref.edit()
editor.putString("favoriteColor", "Blue")
editor.apply()

// Retrieve favorite color
val color = sharedPref.getString("favoriteColor", "White")
println("Favorite color: $color")
  1. Here's a solution for the second exercise:
val url = URL("https://jsonplaceholder.typicode.com/posts")

with(url.openConnection() as HttpURLConnection) {
    requestMethod = "GET"  

    println("Response Code: $responseCode")

    inputStream.bufferedReader().use {
        println(it.lines().collect(Collectors.joining("\n")))
    }
}

Keep practicing and exploring more about Android data storage and fetching!