Skip to content

Android.content.SharedPreferences:Example

Android의 사용자정보(Preference)를 Save/Load할 수 있다.

package ---;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * 사용자 데이터를 저장할 수 있도록 도와주는 클래스.
 * 
 * @author cwlee
 * @since 2013-08-08
 */
public class UserData {

    /** 사용자정보를 저장하거나 불러올 수 있는 Singleton Preferences 객체를 획득한다. */
    private static SharedPreferences getSharedPreferences(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    /** 사용자정보를 편집할 수 있는 Singleton Preferences 객체의 Editor를 획득한다. */
    private static SharedPreferences.Editor getSharedPreferencesEditor(Context context) {
        return getSharedPreferences(context).edit();
    }

    // -----
    // Load.
    // -----

    public static boolean loadBoolean(Context context, String key, boolean default_value) {
        return getSharedPreferences(context).getBoolean(key, default_value);
    }

    public static int loadInt(Context context, String key, int default_value) {
        return getSharedPreferences(context).getInt(key, default_value);
    }

    public static float loadFloat(Context context, String key, float default_value) {
        return getSharedPreferences(context).getFloat(key, default_value);
    }

    public static long loadLong(Context context, String key, long default_value) {
        return getSharedPreferences(context).getLong(key, default_value);
    }

    public static String loadString(Context context, String key, String default_value) {
        return getSharedPreferences(context).getString(key, default_value);
    }

    // -----
    // Save.
    // -----

    public static void saveBoolean(Context context, String key, boolean value) {
        SharedPreferences.Editor localEditor = getSharedPreferencesEditor(context);
        localEditor.putBoolean(key, value);
        localEditor.commit();
    }

    public static void saveInt(Context context, String key, int value) {
        SharedPreferences.Editor localEditor = getSharedPreferencesEditor(context);
        localEditor.putInt(key, value);
        localEditor.commit();
    }

    public static void saveFloat(Context context, String key, float value) {
        SharedPreferences.Editor localEditor = getSharedPreferencesEditor(context);
        localEditor.putFloat(key, value);
        localEditor.commit();
    }

    public static void saveLong(Context context, String key, long value) {
        SharedPreferences.Editor localEditor = getSharedPreferencesEditor(context);
        localEditor.putLong(key, value);
        localEditor.commit();
    }

    public static void saveString(Context context, String key, String value) {
        SharedPreferences.Editor localEditor = getSharedPreferencesEditor(context);
        localEditor.putString(key, value);
        localEditor.commit();
    }
}

See also