如何使用onClickButton更改存储的sharedPreference的值?

时间:2019-06-10 13:45:55

标签: android kotlin sharedpreferences

我创建了一个DTO类,当点击API时,该类将存储在SharedPreference中。我想更改变量promotionBtnClosed onClick关闭按钮的值,并且下次应用程序打开时,该元素将从sharedPreference而不是从DTO中获取值。

 @OnClick(R.id.btnClose)
    fun onClickClose() {
       getBoolean(MERCHANT_PROMOTION, false)
       putBoolean(MERCHANT_PROMOTION, true)
        dismiss()


    }

@Parcelize
@JsonIgnoreProperties(ignoreUnknown = true)
open class MerchantPromotionDTO(

        @JsonProperty("image") var image: ImageUrlsDTO? = null,
        @JsonProperty("cta") var cta: CTADTO? = null,
        @JsonProperty("probability") var probability: Int? = 0,
        @JsonProperty("isDismissible") var isDismissible: Boolean? = true,
        @JsonProperty("showImmediate") var showImmediate: Boolean? = false,
        @JsonProperty("promotionBtnClosed") var promotionBtnClosed: Boolean = false
) : BaseResponseDTO()





 const val MERCHANT_PROMOTION = "merchantPromotion"

    private fun editPreference(editorMethod: (SharedPreferences.Editor) -> Unit) {
        val editor = App.instance?.getSharedPreferences(App.instance?.packageName, Activity.MODE_PRIVATE)?.edit()
        editor?.run {
            editorMethod(editor)
            editor.apply()
        }
    }

    private fun <T> getPreference(getMethod: (SharedPreferences) -> T?, defaultValue: T?): T? {
        val sharedPreferences = App.instance?.getSharedPreferences(App.instance?.packageName, Activity.MODE_PRIVATE)
        return sharedPreferences?.run(getMethod) ?: defaultValue
    }

    fun putBoolean(key: String, value: Boolean) {
        editPreference { it.putBoolean(key, value) }
    }





    fun setPromotionData(promotionData: String) {
        putString(MERCHANT_PROMOTION, promotionData)
    }

    fun getPromotionData(): MerchantPromotionDTO {
        return CommonUtils.getClassUsingDeserializer(getString(MERCHANT_PROMOTION, null), MerchantPromotionDTO())
                ?: MerchantPromotionDTO()
    }

0 个答案:

没有答案