package jackall.moncalc.utils import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import jackall.moncalc.common.PreferenceKeys import jackall.moncalc.common.PreferenceNames /** * SharedPreferencesを管理するクラス * * Created by matsumoto_k on 2017/11/01. */ class MySharedPref(context: Context, val preferenceNames: PreferenceNames) { private var sp: SharedPreferences init { if (preferenceNames == PreferenceNames.DEFAULT) { this.sp = PreferenceManager.getDefaultSharedPreferences(context) } else { this.sp = context.getSharedPreferences(preferenceNames.name, Context.MODE_PRIVATE) } } /** * SharedPreferencesから値を取得する * * @param preferenceKeys 取得する値のkey * @param valueClass 取得する値のClass * @param defaultValue 取得する値のデフォルトの値 * @return */ fun getValue(preferenceKeys: PreferenceKeys, valueClass: Class<*>, defaultValue: Any): Any { if (preferenceKeys.preferenceNames == preferenceNames) { when (valueClass) { Int::class.java -> return sp.getInt(preferenceKeys.key, defaultValue as Int) String::class.java -> return sp.getString(preferenceKeys.key, defaultValue as String) Boolean::class.java -> return sp.getBoolean(preferenceKeys.key, defaultValue as Boolean) Float::class.java -> return sp.getFloat(preferenceKeys.key, defaultValue as Float) } } else { throw IllegalArgumentException() } return -1 } /** * SharedPreferencesに値を保存する * * @param preferenceKeys 保存する値のkey * @param valueClass 保存する値のClass * @param value 保存する値 */ fun putValue(preferenceKeys: PreferenceKeys, valueClass: Class<*>, value: Any) { if (preferenceKeys.preferenceNames == preferenceNames) { when (valueClass) { Int::class.java -> sp.edit().putInt(preferenceKeys.key, value as Int).apply() String::class.java -> sp.edit().putString(preferenceKeys.key, value as String).apply() Boolean::class.java -> sp.edit().putBoolean(preferenceKeys.key, value as Boolean).apply() Float::class.java -> sp.edit().putFloat(preferenceKeys.key, value as Float).apply() } } else { throw IllegalArgumentException() } } }