Kotlin中級#3 Shared Preferenceを簡単に使用できます.


常に新しいオブジェクトを作成すると、コードが長くなり、面白くなくなります.
そこで,どのように統合するかを考えると,次のコードが考えられる.

1.BaseActivityに参加する

  inline fun <reified T> SharedPreferences.get(key: String, defaultValue: T): T {
        when(T::class) {
            Boolean::class -> return this.getBoolean(key, defaultValue as Boolean) as T
            Float::class -> return this.getFloat(key, defaultValue as Float) as T
            Int::class -> return this.getInt(key, defaultValue as Int) as T
            Long::class -> return this.getLong(key, defaultValue as Long) as T
            String::class -> return this.getString(key, defaultValue as String) as T
            else -> {
                if (defaultValue is Set<*>) {
                    return this.getStringSet(key, defaultValue as Set<String>) as T
                }
            }
        }

        return defaultValue
    }

    inline fun <reified T> SharedPreferences.put(key: String, value: T){
        val editor = this.edit()

        when(T::class) {
            Boolean::class -> editor.putBoolean(key, value as Boolean)
            Float::class -> editor.putFloat(key, value as Float)
            Int::class -> editor.putInt(key, value as Int)
            Long::class -> editor.putLong(key, value as Long)
            String::class -> editor.putString(key, value as String)
            else -> {
                if (value is Set<*>) {
                    editor.putStringSet(key, value as Set<String>)
                }
            }
        }

        editor.commit()
    }

2.コール

            getSharedPreferences(getString(R.string.pref_name),MODE_PRIVATE)
            .get(getString(R.string.isfirst), false)   
            
           getSharedPreferences(getString(R.string.pref_name),MODE_PRIVATE)
           .put(getString(R.string.isfirst), true)
            
このようにsharedpreferenceを便利に使用することができる.