sharedpreference中putStringSet和getStringSet的问题

来源:互联网 发布:怎样在淘宝上找优惠券 编辑:程序博客网 时间:2024/05/24 02:45
今儿发现了诡异bug,从api 11开始增加了这个方法

public abstract Set<String> getStringSet (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
listenerThe callback that will run.


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

0 0
原创粉丝点击