Mobile App Development / Android App Development

Fetching and Storing Data in Android Apps

This tutorial will cover how to fetch and store data in Android apps. You'll learn about different data storage options available in Android, and how to interact with APIs to fetc…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Focuses on building mobile applications for the Android platform using Kotlin or Java.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help