sharedpreference中putStringSet和getStringSet的問題

今兒發現了詭異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運行在主線程中!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章