Android SharedPreferences


Android SharedPreferences Tutorial and Examples.

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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post