Kotlin중급 #3 SharedPreference 쉽게 쓰자.

0

항상 새로운 객체를 만들고 하다보면 코드도 길어지고 이쁘지 않다.
그래서 어떻게 합칠까 생각하다가 아래의 코드를 고안해 냈다.

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를 사용할수 있다.

profile
쉽게 가르칠수 있도록 노력하자

0개의 댓글