Working with SharedPreferences

SharedPreferences is an interface for storing, accessing, and modifying data. The SharedPreferences APIs enable data storage in sets of key-value pairs.

We will set up a simple utility to handle our data storage needs for this app utilizing the SharedPreferences interface. Create a package in the project's source directory with the name storage (right-click the source directory and select New | Package):

Next, create a new Kotlin class named AppPreferences within the storage package. Type the following code into the class file:

package com.mydomain.tetris.storage
import android.content.Context
import android.content.SharedPreferences

class AppPreferences(ctx: Context) {

var data: SharedPreferences = ctx.getSharedPreferences
("APP_PREFERENCES", Context.MODE_PRIVATE)

fun saveHighScore(highScore: Int) {
data.edit().putInt("HIGH_SCORE", highScore).apply()
}

fun getHighScore(): Int {
return data.getInt("HIGH_SCORE", 0)
}

fun clearHighScore() {
data.edit().putInt("HIGH_SCORE", 0).apply()
}
}

In the preceding code snippet, a Context is required to be passed to the class' constructor upon creation of an instance of the class. Context provides access to the getSharedPreferences() method, which retrieves a specified preference file. The preference file is identified by the name in the string passed as the getSharedPreferences() method's first argument.

The saveHighScore() function takes an integer – the high score to be saved – as its only argument. data.edit() returns an Editor object that permits the modification of a preference file. The editor's putInt() method is called in order to store an integer within the preference file. The first argument passed to putInt() is a string representing the key that will be used to access the stored value. The second argument to the method is the integer to be stored – in this case, the high score.

getHighScore() returns the high score by calling data.getInt(). getInt() is a function implemented by SharedPreferences that provides read access to a stored integer value. HIGH_SCORE is the unique identifier of the value to be retrieved. The 0 passed to the function's second argument specifies a default value to be returned in the scenario that no value corresponding to the specified key exists.

clearHighScore() resets the high score to zero by simply overwriting the value corresponding to the HIGH_SCORE key with 0.

Now that we have our AppPreferences utility class in place, we can finish up the onBtnResetScoreClick() function in MainActivity:

private fun onBtnResetScoreClick(view: View) {
val preferences = AppPreferences(this)
preferences.clearHighScore()
}

Now when the high score reset button is clicked, the high score is reset to zero. You'll want to give the user some sort of feedback when such actions occur. We can utilize a Snackbar to provide this user feedback.

In order to use the Snackbar class within an Android application, the Android design support library dependency must be added to the module-level Gradle build script. Do this by adding the following line of code under the dependencies closure of build.gradle:

implementation 'com.android.support:design:26.1.0'

After you have added the line, your module-level build.gradle script should look similar to the following:

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

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.mydomain.tetris"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner
.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:
kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:
constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'
// adding android design support library
}

After making the alterations, sync your project by clicking Sync Now on the flash message that appears within the editor window, as shown in the following screenshot:

Without further ado, let's modify our onBtnResetClick() to provide user feedback in the form of a Snackbar after a score reset has been performed by using the following code:

private fun onBtnResetScoreClick(view: View) {
val preferences = AppPreferences(this)
preferences.clearHighScore()
Snackbar.make(view, "Score successfully reset",
Snackbar.LENGTH_SHORT).show()
}

Clicking on RESET SCORE successfully resets the high score of the player as shown in the following screenshot:

Before moving further, you'll want to update the text displayed in the high score text view of the MainActivity layout to reflect the reset score. This can be done by changing the text contained in the text view as follows:

private fun onBtnResetScoreClick(view: View) {
val preferences = AppPreferences(this)
preferences.clearHighScore()
Snackbar.make(view, "Score successfully reset",
Snackbar.LENGTH_SHORT).show()
tvHighScore?.text = "High score: ${preferences.getHighScore()}"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.235.23