SharedPreferences工具类 putStringSet 失效问题注意

SPUtil 工具类实现
注意点:
1.注意HashSet对象引用为同一个,可能不会触发更新。需要拷贝数据到新的Hashset
mBlockCommentIdSet.add(String.valueOf(evaluationId));
Set blockSet = new HashSet<>();
blockSet.addAll(mBlockCommentIdSet);

2.在putStringSet 调用之前,注意先 clear(),不然已经存在该 key了,value值不会更新。
https://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences

object SPUtil {
    
    
    private val prefs : SharedPreferences by lazy {
    
     ApplicationContext.getContext().getSharedPreferences("feedback-sp", Context.MODE_PRIVATE) }

    const val KEY_FEEDBACK_BLOCK = "feedback_block"


    fun putBoolean(key: String, value: Boolean) {
    
    
        with(prefs.edit()) {
    
    
            putBoolean(key, value)
        }.apply()
    }

    fun getBoolean(key: String, defaultValue: Boolean) : Boolean {
    
    
        return with(prefs) {
    
    
            getBoolean(key, defaultValue)
        }
    }

    fun putInt(key: String, value: Int) {
    
    
        with(prefs.edit()) {
    
    
            putInt(key, value)
        }.apply()
    }

    fun getInt(key: String, defaultValue: Int) : Int{
    
    
        return with(prefs) {
    
    
            getInt(key, defaultValue)
        }
    }

    fun putString(key: String, value: String) {
    
    
        with(prefs.edit()) {
    
    
            putString(key, value)
        }.apply()
    }

    fun getString(key: String, defaultValue: String): String? {
    
    
        return with(prefs) {
    
    
            getString(key, defaultValue)
        }
    }

    fun putStringSet(key: String, value: Set<String>) {
    
    
        with(prefs.edit()) {
    
    
            clear() // 注意先clear
            putStringSet(key, value)
        }.apply()
    }

    fun getStringSet(key: String, defaultValue: Set<String>):  Set<String>? {
    
    
        return with(prefs) {
    
    
            getStringSet(key, defaultValue)
        }
    }

}

更新putStringset方法

private void addToBlockList(long evaluationId) {
    
    
        if (evaluationId > 0 && mBlockCommentIdSet != null) {
    
    
            mBlockCommentIdSet.add(String.valueOf(evaluationId));
            Set<String> blockSet = new HashSet<>();
            blockSet.addAll(mBlockCommentIdSet);
            SPUtil.INSTANCE.putStringSet(SPUtil.KEY_FEEDBACK_BLOCK, blockSet);
        }
    }

猜你喜欢

转载自blog.csdn.net/adayabetter/article/details/127701431