Save Data using Shared Preferences in Android

Save Data using Shared Preferences in Android

Shared preferences are used to save and retrieve key-value data. It only allows to save primitive data types: int, long, float, boolean, and string. The data are stored in an XML file in the app data folder:

  • /data/data/<PACKAGE_NAME>/shared_prefs/<PREF_NAME>.xml

To get a SharedPreferences object, we can use one of the following methods:

MethodDescription
getSharedPreferences()Allows to save multiple shared preference files by passing the name as a first parameter.
getPreferences()Used if need to save only one shared preference file for the activity. Class name of the activity will be used to identify a file.

To save data in a shared preference file, we need an Editor. It can be created by edit() method. We can add key-value pair with methods such as putString(key, value), putInt(key, value), etc.

To save changes, use commit() or apply() method. The commit() method writes the data to persistent storage synchronously (blocks the thread). It then returns a boolean value that indicates success or failure. The apply() schedules the data to be written asynchronously. It doesn't return a value that informs about a status of the operation.

To retrieve value from the shared preference file, we need to use methods such as getString(key, defaultValue), getInt(key, defaultValue), etc.

app/src/main/java/com/example/app/MainActivity.java

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
    private static final String prefName = "my_data";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        write("Hello world");
        String message = read();

        Log.d("MY_APP", message);
    }

    private void write(String message)
    {
        SharedPreferences sharedPref = getSharedPreferences(prefName, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        editor.putString("message", message);
        editor.apply();
    }

    private String read()
    {
        SharedPreferences sharedPref = getSharedPreferences(prefName, MODE_PRIVATE);

        return sharedPref.getString("message", "");
    }
}

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity()
{
    private val prefName: String = "my_data"

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

        write("Hello world")
        val message = read()

        Log.d("MY_APP", message!!)
    }

    private fun write(message: String)
    {
        val sharedPref = getSharedPreferences(prefName, MODE_PRIVATE)
        val editor = sharedPref.edit()

        editor.putString("message", message)
        editor.apply()
    }

    private fun read(): String?
    {
        val sharedPref = getSharedPreferences(prefName, MODE_PRIVATE)

        return sharedPref.getString("message", "")
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.