Development/Android

[Android] SharedPreferences 간단하게 활용하는 라이브러리 'Prefs'

SeungYong.Lee 2024. 1. 25. 17:09
반응형

SharedPreferences 정의

SharedPreferences는 안드로이드 애플리케이션에서 간단한 키-값 쌍을 저장하고 검색하기 위한 인터페이스를 제공하는 클래스입니다. 이를 통해 애플리케이션 데이터를 저장하고 필요할 때 검색하여 사용할 수 있습니다.

https://developer.android.com/training/data-storage/shared-preferences?hl=ko

 

SharedPreferences로 단순 데이터 저장하기  |  Android 개발자  |  Android Developers

DataStore는 로컬 데이터를 저장하는 최신 방법을 제공합니다. SharedPreferences 대신 DataStore를 사용해야 합니다. 자세한 내용은 DataStore 가이드를 참고하세요. SharedPreferences로 단순 데이터 저장하기 컬

developer.android.com

 

그리고 아래와 같은 초기 설정과 save를 위한 로직 구성이 필요합니다.

val prefs = getSharedPreferences("TestInfo", MODE_PRIVATE)

val editor: SharedPreferences.Editor = prefs.edit()
editor.putString("SAVE_DATA", value)
editor.apply()
editor.apply()
getPreferences()

 

Prefs 라이브러리

이러한 과정을 조금이나마 축약시켜 활용할 수 있는 라이브러리가 Prefs입니다.

https://github.com/Pixplicity/EasyPrefs

 

GitHub - Pixplicity/EasyPrefs: A small library containing a wrapper/helper for the Shared Preferences of android.

A small library containing a wrapper/helper for the Shared Preferences of android. - GitHub - Pixplicity/EasyPrefs: A small library containing a wrapper/helper for the Shared Preferences of android.

github.com

dependencies {
    implementation 'com.pixplicity.easyprefs:EasyPrefs:1.10.0'
}

 

Gradle Sync 이후, 아래와 같이 초기 설정을 진행합니다.

Prefs.Builder().setContext(this).setMode(MODE_PRIVATE).setPrefsName("TestInfo")
    .setUseDefaultSharedPreference(true).build()


이제 라이브러리 자체에서 제공되는 함수를 통해 개발자는 간단하게 값을 저장 및 추출할 수 있습니다.

/**
 * Stores a boolean value.
 *
 * @param key   The name of the preference to modify.
 * @param value The new value for the preference.
 * @see android.content.SharedPreferences.Editor#putBoolean(String, boolean)
 */
public static void putBoolean(final String key, final boolean value) {
    final Editor editor = getPreferences().edit();
    editor.putBoolean(key, value);
    editor.apply();
}

/**
 * Stores a String value.
 *
 * @param key   The name of the preference to modify.
 * @param value The new value for the preference.
 * @see android.content.SharedPreferences.Editor#putString(String, String)
 */
public static void putString(final String key, final String value) {
    final Editor editor = getPreferences().edit();
}
    
/**
 * Retrieves a stored float value.
 *
 * @param key      The name of the preference to retrieve.
 * @param defValue Value to return if this preference does not exist.
 * @return Returns the preference value if it exists, or defValue.
 * @throws ClassCastException if there is a preference with this name that is not a float.
 * @see android.content.SharedPreferences#getFloat(String, float)
 */
public static float getFloat(final String key, final float defValue) {
    return getPreferences().getFloat(key, defValue);
}

/**
 * Retrieves a stored String value.
 *
 * @param key      The name of the preference to retrieve.
 * @param defValue Value to return if this preference does not exist.
 * @return Returns the preference value if it exists, or defValue.
 * @throws ClassCastException if there is a preference with this name that is not a String.
 * @see android.content.SharedPreferences#getString(String, String)
 */
public static String getString(final String key, final String defValue) {
    return getPreferences().getString(key, defValue);
}
    editor.putString(key, value);
    editor.apply();
}
fun getTime(): Long {
    return Prefs.getInt("SAVE_TIME", System.currentTimeMillis())
}

fun setTime(value: Long) {
    Prefs.putInt("SAVE_TIME", value)
}

값을 추출할 때에는 null인 경우를 고려하여 Default Value를 설정해주어야 합니다.

반응형