SharedPreferences의 모범 사례
Android는 애플리케이션 데이터를 저장하는 여러 가지 방법을 제공합니다.그 중 하나는 Shared Preferences 대상으로 개인 키 값 (key-value) 데이터를 저장하는 것입니다.
모든 논리는 다음 세 가지 클래스를 기반으로 합니다.
SharedPreferences
Shared Preferences가 가장 중요합니다.Editor 대상을 가져오는 인터페이스와 OnSharedPreferenceChangeListener를 추가하거나 제거하는 인터페이스를 제공합니다.
/ parse Preference file   Preference  
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)  
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
//(Preference     map)        map           map     
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener      
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener      
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example      
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener  
        = new SharedPreferences.OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    }
};
Editor
SharedPreferences.Editor는 SharedPreferences 객체 값을 수정하는 인터페이스입니다.Editor의 변경 사항은 일괄 처리되며,commit () 또는 apply () 를 호출했을 때만 원래의sharedPreferences로 복사됩니다.
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
// put values in editor
editor.putBoolean("key", value);  
editor.put..("key", value);
// remove single value by key
editor.remove("key");
// remove all values
editor.clear();
// commit your putted values to the SharedPreferences object synchronously
// returns true if success            true
boolean result = editor.commit();
// do the same as commit() but asynchronously (faster but not safely)
// returns nothing           
editor.apply();
// There are 1000 String values in preferences
SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
// call time = 4 milliseconds         4  
SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
// call time = 0 milliseconds   0
SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);  
// call time = 0 milliseconds   0
first.edit().putInt("key",15).commit();
int firstValue = first.getInt("key",0)); // firstValue is 15  
int secondValue = second.getInt("key",0)); // secondValue is also 15
first.getString("key", null)  
// call time = 147 milliseconds            ,     map 
first.getString("key", null)  
// call time = 0 milliseconds       map   ,       
second.getString("key", null)  
// call time = 0 milliseconds       
third.getString("key", null)  
// call time = 0 milliseconds
public class MigrationManager {  
    private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
    private final static int PREFERENCES_VERSION = 2;
    public static void migrate(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
        checkPreferences(preferences);
    }
    private static void checkPreferences(SharedPreferences thePreferences) {
        final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
        if (oldVersion < PREFERENCES_VERSION) {
            final SharedPreferences.Editor edit = thePreferences.edit();
            edit.clear();
            edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
            edit.commit();
        }
    }
}
// yours preferences        
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
// default preferences   
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
    public class PreferencesManager {
        private static final String PREF_NAME = "com.example.app.PREF_NAME";
        private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
        private static PreferencesManager sInstance;
        private final SharedPreferences mPref;
        private PreferencesManager(Context context) {
            mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        }
        public static synchronized void initializeInstance(Context context) {
            if (sInstance == null) {
                sInstance = new PreferencesManager(context);
            }
        }
        public static synchronized PreferencesManager getInstance() {
            if (sInstance == null) {
                throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
                        " is not initialized, call initializeInstance(..) method first.");
            }
            return sInstance;
        }
        public void setValue(long value) {
            mPref.edit()
                    .putLong(KEY_VALUE, value)
                    .commit();
        }
        public long getValue() {
            return mPref.getLong(KEY_VALUE, 0);
        }
        public void remove(String key) {
            mPref.edit()
                    .remove(key)
                    .commit();
        }
        public boolean clear() {
            return mPref.edit()
                    .clear()
                    .commit();
        }
    }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.