Share
Explore

GSON LAB to demonstate modifying existing GSON records.

Learning Outcomes:

MainActivity.kt which creates, modifies, displays and then depletes 10 records.
Use LOGCat to visualize this occuring. Just regenerate mainactivity.kt in the previous lab.

Here is a modified version of MainActivity.kt that demonstrates creating, modifying, displaying, and depleting 10 Pokémon records using GSON.
This example will use Logcat to visualize the process.
Here's the updated MainActivity.kt:
package com.example.pokemongsonbattle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity : AppCompatActivity() {
private val tag = "PokemonGSONDemo"
private lateinit var pokemonList: MutableList<Pokemon>
private val gson = Gson()

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

createPokemonList()
displayPokemonList("Initial Pokemon List")
modifyPokemonList()
displayPokemonList("Modified Pokemon List")
depletePokemonList()
}

private fun createPokemonList() {
pokemonList = mutableListOf(
Pokemon("Pikachu", 100, 55, 40),
Pokemon("Charmander", 90, 60, 45),
Pokemon("Squirtle", 95, 50, 65),
Pokemon("Bulbasaur", 100, 45, 55),
Pokemon("Jigglypuff", 110, 40, 35),
Pokemon("Meowth", 85, 55, 40),
Pokemon("Psyduck", 90, 50, 50),
Pokemon("Geodude", 100, 70, 80),
Pokemon("Magikarp", 80, 20, 30),
Pokemon("Eevee", 95, 55, 50)
)
Log.d(tag, "Created 10 Pokemon records")
}

private fun displayPokemonList(message: String) {
Log.d(tag, "--- $message ---")
val jsonList = gson.toJson(pokemonList)
Log.d(tag, jsonList)
}

private fun modifyPokemonList() {
pokemonList.forEachIndexed { index, pokemon ->
pokemon.hp += 10
pokemon.attack += 5
Log.d(tag, "Modified Pokemon $index: ${gson.toJson(pokemon)}")
}
}

private fun depletePokemonList() {
while (pokemonList.isNotEmpty()) {
val removed = pokemonList.removeAt(0)
Log.d(tag, "Removed Pokemon: ${gson.toJson(removed)}")
Log.d(tag, "Remaining Pokemon: ${pokemonList.size}")
}
Log.d(tag, "All Pokemon depleted")
}

data class Pokemon(
val name: String,
var hp: Int,
var attack: Int,
val defense: Int
)
}
This updated MainActivity.kt demonstrates the following:
Creating a list of 10 Pokémon records
Displaying the initial list using GSON
Modifying each Pokémon's HP and attack
Displaying the modified list
Depleting the list one Pokémon at a time
All operations are logged using Logcat for visualization.
To run this lab:
Replace the existing MainActivity.kt in your Android Studio project with this code.
Ensure you have the GSON library in your app's build.gradle file:
implementation 'com.google.code.gson:gson:2.8.9'
Run the app on an emulator or device.
Open the Logcat window in Android Studio.
Filter the Logcat output by entering the tag "PokemonGSONDemo" in the search box.
You'll see the Logcat output showing:
The creation of 10 Pokémon records
The initial JSON representation of the list
Individual modifications to each Pokémon
The modified JSON representation of the list
The removal of each Pokémon until the list is depleted
This lab provides a simple yet effective demonstration of creating, modifying, and manipulating data using GSON, while using Logcat to visualize the process.


megaphone

GSON Lab Part 3: Updating the GSON Record


Additional lab for GSON, which creates, modifies, displays and then depletes 10 records.
Demonistrate the use LOGCat to visualize this occuring.
This just replaces the mainactivity.kt in the previous lab.
This lab just runs a series of activities you can view in LogCat - This code does not count on Clicking a button to start.
image.png
Modified version of MainActivity.kt that demonstrates creating, modifying, displaying, and depleting 10 Pokémon records using GSON.
This example will use Logcat to visualize the process.
Here's the updated MainActivity.kt:
package com.example.pokemongsonbattle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity : AppCompatActivity() {
private val tag = "PokemonGSONDemo"
private lateinit var pokemonList: MutableList<Pokemon>
private val gson = Gson()

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

createPokemonList()
displayPokemonList("Initial Pokemon List")
modifyPokemonList()
displayPokemonList("Modified Pokemon List")
depletePokemonList()
}

private fun createPokemonList() {
pokemonList = mutableListOf(
Pokemon("Pikachu", 100, 55, 40),
Pokemon("Charmander", 90, 60, 45),
Pokemon("Squirtle", 95, 50, 65),
Pokemon("Bulbasaur", 100, 45, 55),
Pokemon("Jigglypuff", 110, 40, 35),
Pokemon("Meowth", 85, 55, 40),
Pokemon("Psyduck", 90, 50, 50),
Pokemon("Geodude", 100, 70, 80),
Pokemon("Magikarp", 80, 20, 30),
Pokemon("Eevee", 95, 55, 50)
)
Log.d(tag, "Created 10 Pokemon records")
}

private fun displayPokemonList(message: String) {
Log.d(tag, "--- $message ---")
val jsonList = gson.toJson(pokemonList)
Log.d(tag, jsonList)
}

private fun modifyPokemonList() {
pokemonList.forEachIndexed { index, pokemon ->
pokemon.hp += 10
pokemon.attack += 5
Log.d(tag, "Modified Pokemon $index: ${gson.toJson(pokemon)}")
}
}

private fun depletePokemonList() {
while (pokemonList.isNotEmpty()) {
val removed = pokemonList.removeAt(0)
Log.d(tag, "Removed Pokemon: ${gson.toJson(removed)}")
Log.d(tag, "Remaining Pokemon: ${pokemonList.size}")
}
Log.d(tag, "All Pokemon depleted")
}

data class Pokemon(
val name: String,
var hp: Int,
var attack: Int,
val defense: Int
)
}
This updated MainActivity.kt demonstrates the following:
Creating a list of 10 Pokémon records
Displaying the initial list using GSON
Modifying each Pokémon's HP and attack
Displaying the modified list
Depleting the list one Pokémon at a time
All operations are logged using Logcat for visualization.
To run this lab:
Replace the existing MainActivity.kt in your Android Studio project with this code.
Ensure you have the GSON library in your app's build.gradle file:
implementation 'com.google.code.gson:gson:2.8.9'
Run the app on an emulator or device.
Open the Logcat window in Android Studio.
Filter the Logcat output by entering the tag "PokemonGSONDemo" in the search box.
You'll see the Logcat output showing:
The creation of 10 Pokémon records
The initial JSON representation of the list
Individual modifications to each Pokémon
The modified JSON representation of the list
The removal of each Pokémon until the list is depleted
This lab provides a simple yet effective demonstration of creating, modifying, and manipulating data using GSON, while using Logcat to visualize the process.

Lecture: Understanding GSON Updates and Object Serialization

Introduction

When working with GSON for serialization and deserialization of Java objects, it's important to understand how updates to objects are handled. The key point to remember is that GSON doesn't inherently "update" objects - it simply serializes the current state of an object to JSON, or deserializes JSON to create a new object or populate an existing one.

GSON and Object State

Serialization (Object to JSON):
When you use GSON to convert an object to JSON, it captures the current state of the object.
Any changes made to the object before serialization are reflected in the resulting JSON.
Deserialization (JSON to Object):
When deserializing, GSON creates a new object or updates an existing one based on the JSON data.
It doesn't "update" the JSON itself; rather, it creates or modifies objects based on the JSON data.

Example: Updating an Object

Let's consider a simple Pokemon class:
kotlin
Copy
data class Pokemon(var name: String, var hp: Int)
If we have an instance of this class and modify it:
kotlin
Copy
val pikachu = Pokemon("Pikachu", 100)
val gson = Gson()

// Serialize to JSON
var json = gson.toJson(pikachu)
println(json) // {"name":"Pikachu","hp":100}

// Modify the object
pikachu.hp = 90

// Serialize again
json = gson.toJson(pikachu)
println(json) // {"name":"Pikachu","hp":90}
In this example, GSON is not "updating" anything. It's simply creating a new JSON string that represents the current state of the pikachu object each time toJson() is called.

Misconception: GSON Updating JSON

It's a common misconception that GSON "updates" JSON. In reality:

GSON doesn't maintain any state between serialization calls.
Each toJson() call creates a completely new JSON string based on the current object state.
Each fromJson() call creates a new object or updates an existing one based on the provided JSON.

Implications for Data Management

Understanding this behavior is crucial for effective data management:
If you need to update specific fields in a JSON string, you should:
Deserialize the JSON to an object
Modify the object
Serialize the object back to JSON
For partial updates, you might need to:
Use a custom serializer/deserializer
Implement a merging strategy in your application logic

Conclusion

In summary, GSON doesn't "update" JSON or objects in place. It creates new JSON strings from objects (serialization) or new/updated objects from JSON (deserialization). Any "updates" you see are the result of serializing modified objects or deserializing new JSON data into objects.
This behavior ensures that the JSON always accurately represents the current state of your objects, but it also means that you need to manage object modifications in your application code, not within GSON itself.
This lecture clarifies the common misconception about GSON "updating" data and explains how GSON actually handles object serialization and deserialization. It's important for developers to understand this concept to effectively manage their data when working with GSON and JSON in their applications.
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.