sharedpreference中putStringSet和getStringSet的问题

本文深入探讨了Android Preference的存储机制,特别是关于使用getStringSet方法时的注意事项,以及如何通过注册OnSharedPreferenceChangeListener接口实现对关键操作的监听。文章详细解释了为什么在调用getStringSet方法后不能修改返回的set实例,并提供了解决方案,同时介绍了如何在主线程中监听偏好设置的变化。
今儿发现了诡异bug,从api 11开始增加了这个方法
public abstract Set<StringgetStringSet (String key, Set<String> defValues)
Added in  API level 11


但是用的时候却发现一只无法更新文件中的 数据,百思不得其解之际看了下api文档,有这么一段话

Note that you  must not  modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

为了保证数据一致性,该set实例不能被修改。。。。坑爹么!!


解决办法。。。只能再新建一个,拷贝数据然后修改,再put进去。。我也不明白设计这个接口的人咋想的,o(╯□╰)o

public abstract void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListenerlistener)
Added in  API level 1

Registers a callback to be invoked when a change happens to a preference.

Caution: The preference manager does not currently store a strong reference to the listener. You must store a strong reference to the listener, or it will be susceptible to garbage collection. We recommend you keep a reference to the listener in the instance data of an object that will exist as long as you need the listener.

preference的管理器并不存储一个listener的强引用,你必须指定强引用,否则会被GC回收,建议在listener的生命周期内保持一个对于它实例的引用

Parameters
listener The callback that will run.


偶然发现居然还有这么个接口,
可以监控key的增加删除和改变,需要注意的是该callback运行在主线程中!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值