Share
Explore

Android Application Development: GSON, Shared Preferences, and Objects

Storing and retrieving Objects
What is GSON
Using GSON
How to insert/retrieve a list of objects to SharedPreferences using GSON library (gson.toJSON(), gson.fromJson())
image.png
megaphone

Lab and lecture guide on GSON for storing and retrieving objects.

Lab and Lecture Guide: GSON - Storing and Retrieving Objects
Introduction: In this lab, we'll explore GSON, a powerful library for converting Java objects to JSON and vice versa. We'll use it in conjunction with SharedPreferences to store and retrieve complex objects, something not possible with SharedPreferences alone.
Vertical Theme: Recipe Book App We'll create a simple Recipe Book app where users can add, view, and manage recipes. This theme will help demonstrate the practical use of GSON in a relatable context.
1. What is GSON?
GSON (Google Script Object Notation) is an open-source Java library developed by Google. It allows for seamless serialization of Java objects to JSON and deserialization of JSON strings to Java objects. Key features include:
Simple to use
No need for annotations
Support for complex objects and collections
High performance
2. Using GSON
First, let's set up our project to use GSON:
a) Add the GSON dependency to your app-level build.gradle file:
kotlin
Copy
dependencies {
implementation 'com.google.code.gson:gson:2.10.1'
}
b) Sync your project with the gradle files.
3. How to insert/retrieve a list of objects to SharedPreferences using GSON library
Let's create our Recipe class:
kotlin
Copy
data class Recipe(
val name: String,
val ingredients: List<String>,
val instructions: String,
val preparationTime: Int
)
Now, let's implement the functionality to add, retrieve, and manage recipes using GSON and SharedPreferences:
kotlin
Copy
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity : AppCompatActivity() {
private val sharedPrefFile = "RecipeBookPrefs"
private lateinit var sharedPreferences: SharedPreferences

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

sharedPreferences = getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)

// Example usage
val recipe1 = Recipe("Pasta Carbonara", listOf("Spaghetti", "Eggs", "Bacon", "Parmesan"), "Cook pasta...", 30)
val recipe2 = Recipe("Chicken Stir Fry", listOf("Chicken", "Vegetables", "Soy Sauce"), "Cut chicken...", 25)

saveRecipe(recipe1)
saveRecipe(recipe2)

val allRecipes = getAllRecipes()
println("All Recipes: $allRecipes")

updateRecipe(recipe2.copy(preparationTime = 20))

val updatedRecipes = getAllRecipes()
println("Updated Recipes: $updatedRecipes")

deleteRecipe(recipe1.name)

val remainingRecipes = getAllRecipes()
println("Remaining Recipes: $remainingRecipes")
}

private fun saveRecipe(recipe: Recipe) {
val gson = Gson()
val json = gson.toJson(recipe)
val editor = sharedPreferences.edit()
editor.putString(recipe.name, json)
editor.apply()
}

private fun getRecipe(name: String): Recipe? {
val json = sharedPreferences.getString(name, null)
return if (json != null) {
Gson().fromJson(json, Recipe::class.java)
} else null
}

private fun getAllRecipes(): List<Recipe> {
val gson = Gson()
return sharedPreferences.all.mapNotNull { (_, value) ->
if (value is String) {
gson.fromJson(value, Recipe::class.java)
} else null
}
}

private fun updateRecipe(recipe: Recipe) {
saveRecipe(recipe) // Overwrites the existing recipe
}

private fun deleteRecipe(name: String) {
val editor = sharedPreferences.edit()
editor.remove(name)
editor.apply()
}
}
Explanation of the code:
Saving a Recipe (gson.toJson())
We convert the Recipe object to a JSON string using gson.toJson(recipe).
We then save this JSON string in SharedPreferences using the recipe name as the key.
Retrieving a Recipe (gson.fromJson())
We fetch the JSON string from SharedPreferences using the recipe name.
We then convert this JSON string back to a Recipe object using gson.fromJson(json, Recipe::class.java).
Retrieving All Recipes
We iterate through all entries in SharedPreferences.
For each entry, we convert the JSON string value to a Recipe object.
We use a TypeToken to handle the List<Recipe> type when converting from JSON.
Updating a Recipe
We simply save the updated Recipe object, which overwrites the existing entry in SharedPreferences.
Deleting a Recipe
We remove the entry from SharedPreferences using the recipe name as the key.
Lab Exercise:
Implement a user interface for the Recipe Book app with options to add, view, edit, and delete recipes.
Add functionality to filter recipes based on preparation time or ingredients.
Implement a feature to export all recipes as a JSON file and import recipes from a JSON file.
Conclusion: This lab demonstrates how GSON can be used in conjunction with SharedPreferences to store and retrieve complex objects.

By converting objects to JSON, we can easily persist data that goes beyond simple key-value pairs. This technique is particularly useful for apps that need to store structured data locally without the complexity of a full database solution.
Remember, while this approach works well for small to medium datasets, for larger amounts of data or more complex querying needs, you might want to consider using a proper database solution like Room.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.