Since API level 1, basically the beginning of android, an API for storing Key value pairs has been avaialable in android. This API If you are new to android or is learning how to use sharedpreferences.

In this tutorial we will look at several examples of how to use sharedpreferences to store and retrieve data. Mostly we will be storing primitive dtaa types in our sharedpreferences.

Example 1: Kotlin Android – SharedPreferences Example

This is a simple sharedpreferences example written in Kotlin.

Demo

Here is the demo of what is created:

Kotlin Android Shared Preferences Example

Step 1: Dependencies

No special or third party dependencies are necessary.

Step 2: Design Layout

Design your xml layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:textColor="#101010"
        android:textSize="25sp"/>

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_a_text"
        android:layout_margin="10dp"
        android:textColor="#101010"/>

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/save"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show"
        android:layout_margin="10dp"/>

</LinearLayout>

Step 3: Write Code

Then write your kotlin code as follows:

MainActivity.kt

Here is the full code for main activity:

package arb.test.shared.perferences

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var shared : SharedPreferences

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

        shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)

        save.setOnClickListener {

            val edit = shared.edit()
            edit.putString("txt" , edt.text.toString())
            Toast.makeText(this , "Was Saved" , Toast.LENGTH_SHORT).show()
            edit.apply()
        }

        show.setOnClickListener {

            txt.text = shared.getString("txt" , "No imported" )
            Toast.makeText(this ,  shared.getString("txt" , "No imported" ) , Toast.LENGTH_SHORT).show()
        }

    }
}

Run

Run the project

References

Here are the download links:

No. Link
1. Dowload Code
2. Browse Code
3. Follow code author

Example 2: Session Management using SharedPreferences

In this example you will learn how to manage user sessions, for example after a user signs into the app, using SharedPreferences. This example is also written in Kotlin.

It contains these three files:

  1. Two Activities – First and Login Activities.
  2. Sesson Manager – SharedPreferences class

Let’s start.

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

No external dependencies are needed for this project.

Step 3: Design Layouts.

We will design two layouts:

(a). activity_login.xml

This is the login activity. Add two TextViews and a Button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/Disp_Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Username"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:id="@+id/Disp_Password"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"/>

    <Button
        android:id="@+id/btnLogout"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:text="Logout"/>

</LinearLayout>

(b). activity_first.xml

This is the layout for the main activity. Add a Button and two edittexts:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".FirstActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Session Management"
        android:textColor="@color/colorPrimary"
        android:textSize="30sp"/>

    <EditText
        android:id="@+id/txtUsername"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Username"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <EditText
        android:id="@+id/txtPassword"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Password"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <Button
        android:id="@+id/btnLogin"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:text="Login"
        android:textColor="@android:color/white"
        android:background="@color/colorPrimary"/>

</LinearLayout>

Step 4: Create Session Manager

Create session manager using sharedpreferences. Start by creating the file SessionManager.kt along with the following instance fields: a SharedPreferences object, a SharedPreferences.Editor object, a Context object and an integer to represent the private mode:

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

Initialize them in the constructor:

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

Define static fields in a companion object:

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

Here is how you create a login session:

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

Here is how you check the login:

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

Here is how you get the user details from the sharedpreferences and return them in a HashMap:

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

Here is how you log out a user:

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

And here is how you check if a user is logged in:


    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

Here is the full code:

SessionManager.kt

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.example.sessionmanagementusingkotlin.FirstActivity
import com.example.sessionmanagementusingkotlin.LoginActivity

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

}

Step 5: Create Activities

We have two activities:

(a). FirstActivity.kt

Will login a user and save his/her details in SharedPreferences:

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.sdnkcreations.sessionmanagerinkotlin.SessionManager
import kotlinx.android.synthetic.main.activity_first.*

class FirstActivity : AppCompatActivity() {

    lateinit var session: SessionManager

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

        session = SessionManager(applicationContext)
        if (session.isLoggedIn()) {
            var i: Intent = Intent(applicationContext, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(i)
            finish()
        }

        btnLogin.setOnClickListener {

            val username: String = txtUsername.text.toString()
            val password: String = txtPassword.text.toString()

            if (username.trim().length > 0 && password.trim().length > 0) {

                session.createLoginSession(username, password)
                var i: Intent = Intent(applicationContext, LoginActivity::class.java)
                startActivity(i)
                finish()

            } else {

                Toast.makeText(this, "Login Failed...\n Please enter both credential", Toast.LENGTH_LONG).show()
            }

        }
    }
}

(b). LoginActivity.kt

Will display the details of a Logged In user:

class LoginActivity : AppCompatActivity() {

    lateinit var session: SessionManager

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

        session = SessionManager(applicationContext)
        session.checkLogin()

        val user: HashMap<String, String> = session.getUserDetails()

        val name: String = user.get(SessionManager.KEY_NAME)!!
        val pass: String = user.get(SessionManager.KEY_PASS)!!

        Disp_Username.setText("Name: " + name)
        Disp_Password.setText("Email: " + pass)
        btnLogout.setOnClickListener {

            session.LogoutUser()
        }
    }
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

SharedPreferences Snippets

In this tutorial we want to look at SharedPreferences, what it is, why it’s important and several examples.

Here are some SharedPreferences examples.

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.MainThread;

import com.jiangkang.tools.King;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

public class SpUtils {

    private SharedPreferences preferences;
    private static final String DEFAULT_PREF_NAME = "ktools_pref";
    private SharedPreferences.Editor editor;

    public static SpUtils getInstance(Context context,String name){
        return new SpUtils(context,name);
    }

    private SpUtils(Context context, String name) {
        preferences = context.getSharedPreferences(name,Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public <T> SpUtils put(String key, T value){
        if (value instanceof String){
            editor.putString(key, (String) value);
        }else if (value instanceof Boolean){
            editor.putBoolean(key, (Boolean) value);
        }else if (value instanceof Integer){
            editor.putInt(key, (Integer) value);
        }else if (value instanceof Long){
            editor.putLong(key, (Long) value);
        }else if (value instanceof Float){
            editor.putFloat(key, (Float) value);
        }else {
            throw new IllegalArgumentException("value can not support");
        }
        return this;
    }

    public SpUtils putString(String key, String value){
        editor.putString(key,value).commit();
        return this;
    }

    public SpUtils putBoolean(String key, boolean value){
        editor.putBoolean(key, value).commit();
        return this;
    }

    public SpUtils putInt(String key, int value){
        editor.putInt(key,value).commit();
        return this;
    }

    public SpUtils putFloat(String key, float value){
        editor.putFloat(key, value).commit();
        return this;
    }

    public SpUtils putLong(String key, long value){
        editor.putLong(key, value).commit();
        return this;
    }

    public SpUtils putJsonObject(String key, JSONObject object){
        editor.putString(key,object.toString());
        return this;
    }

    public JSONObject getJsonObject(String key){
        String jsonString = preferences.getString(key,"{}");
        try {
            return new JSONObject(jsonString);
        } catch (JSONException e) {
            return null;
        }
    }

    public String getString(String key,String defaultValue){
        return preferences.getString(key,defaultValue);
    }

    public boolean getBoolean(String key, boolean defaultValue){
        return preferences.getBoolean(key, defaultValue);
    }

    public int getInt(String key, int defaultValue){
        return preferences.getInt(key, defaultValue);
    }

    public long getLong(String key, long defaultValue){
        return preferences.getLong(key, defaultValue);
    }

    public float getFloat(String key,float defaultValue){
        return preferences.getFloat(key, defaultValue);
    }

    public Map<String,?> getAll(){
        return preferences.getAll();
    }

}
2. How to save and retrieve JSON data in SharedPreference

Let’s start by creating our main application.

This class is deriving from the Application class. All it will do for us is hold and give us the to the application Context.

import android.app.Application;
import android.content.Context;

public class MainApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

Then having created our application class we can now come and save and load our json data.

The first method is the save() method. It will receive two strings and an Object.

We are using the Google Gson library. It’s a third party library so has to be added as a dependency in your app level build.gradle file.

So you go to your build.gradle file(located in the app folder) and add the following line under the dependencies closure:

implementation 'com.google.code.gson:gson:2.8.1'

Maybe you can check for the later versions.

Then once we’ve synced the project we start by instantiating our Gson;

        Gson gson = new Gson();

Then get our SharedPreferences:

        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);

Then obtain a SharedPreference.Editor object by invoking the edit() method of our SharedPreferences class.

        SharedPreferences.Editor editor = pref.edit();

Then convert our object to JSON using the toJson() method of Gson class. Then put that JSON data alongside the key to our SharedPreference.Editor instance, and invoke the apply() method:

        editor.putString(key, gson.toJson(object));
        editor.apply();

That’s how we save the JSON data to SharedPreferences.

What about loading that data? Well we can also easily load that data. Again you instantiate the Gson and initialize our SharedPreferences.

We then get our data as a JSON string by invoking the getString() method of the SharedPreferences class, making sure to pass the key:

        String json = pref.getString(key, null);

We check for null value, in which case we return null. Otherwise we use the fromJson() method of the Gson class to get our object.

Here’s the code:

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.slotnslot.slotnslot.MainApplication;

public class StorageUtil {
    public static void save(String identifier, String key, Object object) {
        Gson gson = new Gson();
        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, gson.toJson(object));
        editor.apply();
    }

    public static <T> T load(String identifier, String key, Class<T> clazz) {
        Gson gson = new Gson();
        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
        String json = pref.getString(key, null);
        return json == null ? null : gson.fromJson(json, clazz);
    }
}