Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Singleton Class To Manage Android SharedPreferences

i am trying to write a singleton class to oversee all operations involving shared preferences.

I have 3 preference files, general, settings, and temp

I want to be able to use this class to write a preference of a given type, for example:

stg_full_screen: true // as boolean

This is what i have done so far:

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPrefManager extends Activity {

    // Globals
    private int GENERAL             = 1000;
    private int SETTINGS            = 2000;
    private int TEMP_STORE          = 3000;

    private String PREF_GENERAL     = "com.example.general";
    private String PREF_SETTINGS    = "com.example.settings";
    private String PREF_TEMP_STORE  = "com.example.temp_store";


    private SharedPreferences general;
    private SharedPreferences settings;
    private SharedPreferences tempStore;

    private SharedPreferences.Editor general_editor;
    private SharedPreferences.Editor settings_editor;
    private SharedPreferences.Editor temp_store_editor;





    // Instantiate singleton object
    private static SharedPrefManager ourInstance = new SharedPrefManager();


    public static SharedPrefManager getInstance() { return ourInstance; }

    private SharedPrefManager() {
        // Get handle on all preference files
        general   = getSharedPreferences(PREF_GENERAL, Context.MODE_PRIVATE);
        settings  = getSharedPreferences(PREF_SETTINGS, Context.MODE_PRIVATE);
        tempStore = getSharedPreferences(PREF_TEMP_STORE, Context.MODE_PRIVATE);

        // provision editors for all preference files
        general_editor    = general.edit();
        settings_editor   = settings.edit();
        temp_store_editor = tempStore.edit();
    }



    private String read_prefs (String pref_name) {
        // this method reads a preference and returns it
        // ideally, i would want to be able to return appropriate types by request
        // e.g boolean, string
        return null;
    }

    private void write_prefs (String pref_name, String pref_val) {
        // this method would take a preference and write the appropriate type to prefs
    }


    // this method determines where to put a preference by checking the name of the key
    // this works because i use the following naming conventions
    // stg_name for settings, tmp_name for all that goes into tempStore

    private String resolve_pref_category (String path) {
        if (path.startsWith("stn"))         return PREF_SETTINGS;
        else if (path.startsWith("tmp"))    return PREF_TEMP_STORE;
        else                                return PREF_GENERAL;
    }

}

My question is:

  1. Is this a wise thing to do?
  2. How can i efficiently determine the type of a preference?

Thanks

like image 762
SamAko Avatar asked Oct 26 '13 23:10

SamAko


People also ask

Is SharedPreferences a singleton?

I've noticed that a lot of projects have their SharedPreferences code scattered all over the project. The reason for this mostly is that fetching SharedPreference and reading/writing preferences as and when needed is the easiest thing to do when writing an app.

How do I write to SharedPreferences?

To write to a shared preferences file, create a SharedPreferences. Editor by calling edit() on your SharedPreferences . Note: You can edit shared preferences in a more secure way by calling the edit() method on an EncryptedSharedPreferences object instead of on a SharedPreferences object.

Is SharedPreferences thread safe?

The SharedPreferences implementation in Android is thread-safe but not process-safe. Normally your app will run all in the same process, but it's possible for you to configure it in the AndroidManifest. xml so, say, the service runs in a separate process than, say, the activity.

Can we store HashMap in SharedPreferences?

Android App Development for Beginners This example demonstrates about How can I save a HashMap to Shared Preferences in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.


1 Answers

Proper Singleton Shared Preferences Class. it may help others in the future.

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

Write data

    SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
    SharedPref.write(SharedPref.AGE, "25");//save int in shared preference.
    SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

Read Data

    String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
    String age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
    String isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

Output

Name : "XXXX";
Age : "25";
IsSelect : "true";
like image 140
Magesh Pandian Avatar answered Oct 27 '22 12:10

Magesh Pandian