Kotlin Android SharedPreferences Examples

Android SharedPreferences Tutorial and Examples

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

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);
    }
}

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code