kotlin android app development course, storing in shared preferences

Hello! Today, we will take a closer look at an important topic in Android app development: “Shared Preferences.” Shared Preferences is one of Android’s built-in methods for data storage that helps you save data as simple key-value pairs. It is primarily useful for storing user settings or simple data.

1. What are Shared Preferences?

Shared Preferences is an API used for storing small amounts of data within an Android application. It is suitable for storing basic data types such as strings, integers, and booleans. This data is retained even when the app is closed or restarted, allowing users to save and retrieve their settings information.

2. When to Use

Shared Preferences is useful in the following cases:

  • Storing user login information
  • User settings (theme, language, notification preferences, etc.)
  • Maintaining the app’s state (e.g., last viewed page)

3. Basic Setup for Using Shared Preferences

To use Shared Preferences, you first need to create an instance through the application context. Here’s a basic usage example:

3.1. Creating a SharedPreferences Instance

val sharedPreferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)

Here, “MyPreferences” is the name of the data you want to store.

4. Saving Data

Here is how to save data in Shared Preferences:

4.1. Saving a String

val editor = sharedPreferences.edit()
editor.putString("username", "JohnDoe")
editor.apply()

4.2. Saving an Integer

val editor = sharedPreferences.edit()
editor.putInt("userAge", 30)
editor.apply()

4.3. Saving a Boolean Value

val editor = sharedPreferences.edit()
editor.putBoolean("notificationsEnabled", true)
editor.apply()

5. Reading Data

Here’s how to read the saved data:

5.1. Reading a String

val username = sharedPreferences.getString("username", "defaultUser")

5.2. Reading an Integer

val userAge = sharedPreferences.getInt("userAge", 0)

5.3. Reading a Boolean Value

val notificationsEnabled = sharedPreferences.getBoolean("notificationsEnabled", false)

6. Deleting Data

If you want to delete specific data, you can do it as follows:

val editor = sharedPreferences.edit()
editor.remove("username")
editor.apply()

7. Deleting All Data

To delete all data, you can use the clear() method:

val editor = sharedPreferences.edit()
editor.clear()
editor.apply()

8. Example: Saving User Settings

Now, let’s go through a simple example of saving and loading user settings. First, create a new project in Android Studio. We will create a simple UI that takes the user’s name and age and saves it in Shared Preferences.

8.1. Layout File

Modify the res/layout/activity_main.xml file as follows:

<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="Username"/>

    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="User Age"
        android:inputType="number"/>

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

    <Button
        android:id="@+id/buttonLoad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load"/>

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"/>

</LinearLayout>

8.2. MainActivity.kt File

Now, modify the MainActivity.kt file to save and load user input:

import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var usernameEditText: EditText
    private lateinit var ageEditText: EditText
    private lateinit var saveButton: Button
    private lateinit var loadButton: Button
    private lateinit var resultTextView: TextView

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

        sharedPreferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
        usernameEditText = findViewById(R.id.editTextUsername)
        ageEditText = findViewById(R.id.editTextAge)
        saveButton = findViewById(R.id.buttonSave)
        loadButton = findViewById(R.id.buttonLoad)
        resultTextView = findViewById(R.id.textViewResult)

        saveButton.setOnClickListener { saveData() }
        loadButton.setOnClickListener { loadData() }
    }

    private fun saveData() {
        val editor = sharedPreferences.edit()
        val username = usernameEditText.text.toString()
        val userAge = ageEditText.text.toString().toIntOrNull() ?: 0

        editor.putString("username", username)
        editor.putInt("userAge", userAge)
        editor.apply()

        resultTextView.text = "Saved: $username, Age: $userAge"
    }

    private fun loadData() {
        val username = sharedPreferences.getString("username", "defaultUser")
        val userAge = sharedPreferences.getInt("userAge", 0)

        resultTextView.text = "Loaded: $username, Age: $userAge"
    }
}

8.3. Running the App

Now run the app. After entering the username and age, clicking the ‘Save’ button will save the data to Preferences. Clicking the ‘Load’ button will display the saved data.

9. Tips and Precautions

  • Do not use Shared Preferences to store sensitive information such as passwords. For data where security is crucial, other data storage methods should be considered.
  • Shared Preferences is suitable for small amounts of data. If you need to store large amounts of data or complex data structures, it is recommended to use an SQLite database or Room library.
  • To reflect data changes immediately, you can use commit() instead of apply(), but this may block the UI thread and should be avoided.

10. Conclusion

In this tutorial, we learned how to use Shared Preferences in Android app development. We can easily save and load user settings through Preferences. By knowing various data storage methods and applying them in appropriate situations, broader app development becomes possible.

Now, try utilizing Shared Preferences to enhance user experience in your own apps. In the next tutorial, we will cover more advanced data storage methods. Thank you!