Last active
November 22, 2017 09:14
-
-
Save pjhjohn/39c358363fd04f3603a23e8107cdbe20 to your computer and use it in GitHub Desktop.
Utility Object for Easy Use of SharedPreferences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.sample.utils | |
import android.annotation.SuppressLint | |
import android.content.Context | |
import android.content.SharedPreferences | |
import io.sample.App | |
import java.util.* | |
object Storage { | |
private fun local(): SharedPreferences { | |
val context = App.context() | |
return context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE) | |
} | |
/* SharedPreference Method Mapping */ | |
operator fun contains(key: String): Boolean = Storage.local().contains(key) | |
val all: Map<String, *> get() = Storage.local().all | |
fun getBoolean(key: String, fallback: Boolean): Boolean = Storage.local().getBoolean(key, fallback) | |
fun getFloat(key: String, fallback: Float): Float = Storage.local().getFloat(key, fallback) | |
fun getInt(key: String, fallback: Int): Int = Storage.local().getInt(key, fallback) | |
fun getLong(key: String, fallback: Long): Long = Storage.local().getLong(key, fallback) | |
fun getString(key: String, fallback: String): String = Storage.local().getString(key, fallback) | |
fun getNullableString(key: String, fallback: String? = null): String? = Storage.local().getString(key, fallback) | |
/* SharedPreferences.Editor Method Mapping */ | |
fun remove(key: String) = Storage.local().edit().remove(key).apply() | |
fun clear() = Storage.local().edit().clear().apply() | |
@SuppressLint("CommitPrefEdits") | |
fun put(pair: Pair<Any?, String>): Any? = with(Storage.local().edit()) { | |
val value = pair.first | |
val key = pair.second | |
when (value) { | |
is Boolean -> putBoolean(key, value) | |
is Float -> putFloat(key, value) | |
is Int -> putInt(key, value) | |
is Long -> putLong(key, value) | |
is String -> putString(key, value) | |
null -> remove(key) | |
else -> InputMismatchException("Only primitive types can be stored in SharedPreferences") | |
} | |
apply() | |
value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment