Guest User

Untitled

a guest
Nov 14th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. import android.content.SharedPreferences
  2. import android.text.TextUtils
  3. import java.security.spec.InvalidParameterSpecException
  4.  
  5. /**
  6. * Return value on the given key.
  7. * [T] is the type of value
  8. * @param defaultValue optional default value
  9. */
  10. inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T {
  11. return when (T::class) {
  12. String::class -> getString(key, defaultValue as? String) as T
  13. Int::class -> getInt(key, defaultValue as? Int ?: -1) as T
  14. Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T
  15. Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T
  16. Long::class -> getLong(key, defaultValue as? Long ?: -1) as T
  17. else -> throw UnsupportedOperationException("Not yet implemented")
  18. }
  19. }
  20.  
  21. /**
  22. * Puts a key value pair in SharedPreferences if doesn't exists, otherwise updates value on given [key]
  23. */
  24. @Suppress("UNCHECKED_CAST")
  25. inline operator fun <reified T> SharedPreferences.set(key: String, value: T) {
  26. if (TextUtils.isEmpty(key)) {
  27. throw InvalidParameterSpecException("Invalid key")
  28. }
  29.  
  30. val editor = this.edit()
  31. when (value) {
  32. is Boolean -> editor.putBoolean(key, value as Boolean)
  33. is Float -> editor.putFloat(key, value as Float)
  34. is Int -> editor.putInt(key, value as Int)
  35. is Long -> editor.putLong(key, value as Long)
  36. is String -> editor.putString(key, value as String)
  37. is Set<*> -> editor.putStringSet(key, value as Set<String>)
  38. else -> throw UnsupportedOperationException("Not yet implemented")
  39. }
  40. editor.apply()
  41. }
Add Comment
Please, Sign In to add comment