Share
Explore

New High Score

Let’s modify the code for Lab 2 (Exercise 2: Update and Remove a High Score with SharedPreferences) to update the displayed high score only if the user’s input is higher than the current high score. If the input is not higher, we’ll display a Toast message to inform the user.

Modified Code for Exercise 2

Objective

Practice updating and removing data using SharedPreferences, with the added condition that the high score is only updated if the new score is higher than the current high score, otherwise displaying a Toast message.

Task

Modify the app to compare the user’s input high score with the current high score.
Update the high score and TextView only if the new score is higher.
If the new score is not higher, display a Toast message: “New entry is not higher than the current high score.”
Retain the ability to remove the high score.

Updated Code

Note: The layout (activity_main.xml) remains unchanged from the original Exercise 2, as it already includes all necessary UI elements (EditText, Buttons, TextView).
The package name in the provided code (com.example.usernamestorageapp) doesn’t match the app name (HighScoreApp), but I’ll correct it to match the original Exercise 2 setup (com.example.highscoreapp) for consistency.
Updated MainActivity.kt
Replace app/src/main/java/com/example/highscoreapp/MainActivity.kt with the following modified code:

package com.example.highscoreapp

import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.highscoreapp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var sharedPreferences: SharedPreferences

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

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 high score
val savedHighScore = sharedPreferences.getInt("highScore", 0)
binding.textViewHighScore.text = "High Score: $savedHighScore"

// Save or update high score on button click, only if new score is higher
binding.buttonSaveScore.setOnClickListener {
val newHighScore = binding.editTextHighScore.text.toString().toIntOrNull() ?: 0
val currentHighScore = sharedPreferences.getInt("highScore", 0)
if (newHighScore > currentHighScore) {
val editor = sharedPreferences.edit()
editor.putInt("highScore", newHighScore)
editor.apply()
binding.textViewHighScore.text = "High Score: $newHighScore"
} else {
Toast.makeText(
this,
"New entry is not higher than the current high score.",
Toast.LENGTH_SHORT
).show()
}
binding.editTextHighScore.text.clear()
}

// Remove high score on button click
binding.buttonRemoveScore.setOnClickListener {
val editor = sharedPreferences.edit()
editor.remove("highScore")
editor.apply()
binding.textViewHighScore.text = "High Score: 0"
}
}
}

Changes Made

Compare New Score with Current Score:
Added currentHighScore = sharedPreferences.getInt("highScore", 0) to retrieve the current high score.
Used an if condition (newHighScore > currentHighScore) to check if the new score is higher.
Update High Score Only if Higher:
If the new score is higher, the code updates SharedPreferences and the TextView as before.
If not, the update is skipped, and a Toast message is displayed.
Display Toast Message:
Added Toast.makeText() to show the message “New entry is not higher than the current high score.” when the condition fails.
Used Toast.LENGTH_SHORT for a brief display (about 2 seconds).
Retained Existing Functionality:
The “Remove High Score” button functionality remains unchanged.
The editTextHighScore is cleared after each save attempt, whether successful or not.

Expected Behavior

The app starts with "High Score: 0".
Enter a high score (e.g., 100) and click "Save High Score"—the TextView updates to "High Score: 100".
Enter a lower score (e.g., 50)—a Toast message appears: “New entry is not higher than the current high score,” and the TextView remains "High Score: 100".
Enter a higher score (e.g., 150)—the TextView updates to "High Score: 150".
Click "Remove High Score"—the TextView resets to "High Score: 0".
The high score persists across app restarts.



res/layout/activity_main.xml:

<?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/editTextHighScore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter high score"
android:inputType="number" />

<Button
android:id="@+id/buttonSaveScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save High Score" />

<Button
android:id="@+id/buttonRemoveScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove High Score" />

<TextView
android:id="@+id/textViewHighScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="High Score: 0"
android:textSize="16sp" />

</LinearLayout>
app/src/main/java/com/example/highscoreapp/MainActivity.kt:

package com.example.highscoreapp

import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.highscoreapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var sharedPreferences: SharedPreferences

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

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 high score
val savedHighScore = sharedPreferences.getInt("highScore", 0)
binding.textViewHighScore.text = "High Score: $savedHighScore"

// Save or update high score on button click, only if new score is higher
binding.buttonSaveScore.setOnClickListener {
val newHighScore = binding.editTextHighScore.text.toString().toIntOrNull() ?: 0
val currentHighScore = sharedPreferences.getInt("highScore", 0)
if (newHighScore > currentHighScore) {
val editor = sharedPreferences.edit()
editor.putInt("highScore", newHighScore)
editor.apply()
binding.textViewHighScore.text = "High Score: $newHighScore"
} else {
Toast.makeText(
this,
"New entry is not higher than the current high score.",
Toast.LENGTH_SHORT
).show()
}
binding.editTextHighScore.text.clear()
}

// Remove high score on button click
binding.buttonRemoveScore.setOnClickListener {
val editor = sharedPreferences.edit()
editor.remove("highScore")
editor.apply()
binding.textViewHighScore.text = "High Score: 0"
}
}
}
Expected Behavior:
The app starts with "High Score: 0".
Enter a high score (e.g., 100) and click "Save High Score"—the TextView updates to "High Score: 100".
Enter a lower score (e.g., 50)—a Toast message appears: “New entry is not higher than the current high score,” and the TextView remains "High Score: 100".
Enter a higher score (e.g., 150)—the TextView updates to "High Score: 150".
Click "Remove High Score"—the TextView resets to "High Score: 0".
The high score persists across app restarts.


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.