Share
Explore

Lab Sheet for Exercise 3: Save and Retrieve a User Object with GSON

Standalone Lab Sheet for Exercise 3: Save and Retrieve a User Object with GSON

Objective: Practice saving and retrieving a single object using GSON and SharedPreferences in an Android app.
Task:
Create an app with a simple UI: an EditText for the user’s name, an EditText for the user’s age, a Button to save the user, and a TextView to display the saved user.
Save a User object to SharedPreferences using GSON when the button is clicked.
Display the saved user in the TextView when the app starts.

Step 1: Create a New Android Project

Start Fresh:
Close Android Studio and reboot your computer to ensure a clean slate.
Open Android Studio after rebooting.
Create a New Project:
In Android Studio, go to File > New > New Project.
Select Empty Activity.
Configure the project:
Name: UserStorageApp
Package name: com.example.userstorageapp
Save location: Default (e.g., C:\AndroidStudioProjects\UserStorageApp)
Language: Kotlin
Minimum API: 24 (Nougat)
Click Finish to create the project.

Step 2: Configure Gradle Files

To avoid Gradle sync issues, we’ll use a simplified Gradle setup with explicit dependency declarations (avoiding the Version Catalog for now) and ensure compatibility with a modern Gradle version.
Update build.gradle (Project: UserStorageApp):
Open build.gradle (Project: UserStorageApp) and replace its content with:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.1.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.10'
}
}

allprojects {
repositories {
google()
mavenCentral()
}
}
Update build.gradle (Module: app):
Open build.gradle (Module: app) and replace its content with:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
namespace = "com.example.userstorageapp"
compileSdk 35

defaultConfig {
applicationId "com.example.userstorageapp"
minSdk 24
targetSdk 35
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

buildFeatures {
viewBinding true
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}

kotlinOptions {
jvmTarget = "11"
}
}

dependencies {
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.activity:activity-ktx:1.8.2'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.code.gson:gson:2.10.1'

testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
Update gradle-wrapper.properties:
Open gradle/wrapper/gradle-wrapper.properties and ensure it uses Gradle 8.9:
properties
CollapseWrapCopy
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Sync the Project:
Click the Sync Project with Gradle Files button (the elephant icon in the toolbar, or File > Sync Project with Gradle Files).
Wait for the sync to complete. This should succeed without errors.

Step 3: Add the Exercise 3 Code

Create User.kt:
In the Project view, right-click on app/src/main/java/com/example/userstorageapp, select New > Kotlin Class/File, name it User, and add:
kotlin
CollapseWrapCopy
package com.example.userstorageapp

data class User(val name: String, val age: Int)
Update the Layout (activity_main.xml):
Open res/layout/activity_main.xml and replace its content with:
xml
CollapseWrapCopy
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/editTextUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter user name" />

<EditText
android:id="@+id/editTextUserAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter user age"
android:inputType="number" />

<Button
android:id="@+id/buttonSaveUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save User" />

<TextView
android:id="@+id/textViewSavedUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saved User: None"
android:textSize="16sp" />

</LinearLayout>
Update MainActivity.kt:
Open app/src/main/java/com/example/userstorageapp/MainActivity.kt and replace its content with:
kotlin
CollapseWrapCopy
package com.example.userstorageapp

import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.userstorageapp.databinding.ActivityMainBinding
import com.google.gson.Gson

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var sharedPreferences: SharedPreferences
private val gson = Gson()

companion object {
private const val PREFS_NAME = "UserPrefs"
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

// Initialize SharedPreferences
sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)

// Display saved user
val userJson = sharedPreferences.getString("user", null)
val savedUser = userJson?.let { gson.fromJson(it, User::class.java) } ?: User("None", 0)
binding.textViewSavedUser.text = "Saved User: ${savedUser.name}, Age: ${savedUser.age}"

// Save user on button click
binding.buttonSaveUser.setOnClickListener {
val userName = binding.editTextUserName.text.toString()
val userAge = binding.editTextUserAge.text.toString().toIntOrNull() ?: 0
if (userName.isNotBlank()) {
val user = User(userName, userAge)
val userJson = gson.toJson(user)
val editor = sharedPreferences.edit()
editor.putString("user", userJson)
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.