본문 바로가기

Android

[Android]SharedPreferences 간단 사용법

반응형
/**
 * 사용자 정의 SharedPreferences
 * Created by JuDH
 */

public class StorageHelper {
    public static final String STORAGE_KEY = "pref"; // 저장소 메인 키
    Context context;

    private static StorageHelper ourInstance = new StorageHelper();
    public static StorageHelper getInstance() {
        return ourInstance;
    }
    private StorageHelper() {
    }
    public void setContext(Context context) {
        this.context = context;
    }

    public void setString(Context context, String key, String value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(STORAGE_KEY, 0).edit();  // 저장소 획득
        editor.putString(key, value); // 저장
        editor.commit(); // 커밋
    }
    public String getString(Context context, String key) {
        return context.getSharedPreferences(STORAGE_KEY, 0).getString(key, "");
    }

    public void setInt(Context context, String key, int value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(STORAGE_KEY, 0).edit();
        editor.putInt(key, value);
        editor.commit();
    }
    public int getInt(Context context, String key) {
        return context.getSharedPreferences(STORAGE_KEY, 0).getInt(key, 0);
    }
    public void setBoolean(Context context, String key, boolean value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(STORAGE_KEY, 0).edit();
        editor.putBoolean(key, value);
        editor.commit();
    }
    public boolean getBoolean(Context context, String key) {
        return context.getSharedPreferences(STORAGE_KEY, 0).getBoolean(key, false);
    }
}



싱글톤으로 생성한 후


사용하면 됩니다.

반응형