关于SharedPreferences中无法改变Set的问题。

本文讨论了在Android项目中使用SharedPreferences管理历史输入记录时遇到的问题,特别是在使用getStringSet方法获取Set集合后,如何正确地更新并保存到SharedPreferences中。通过分析API文档和示例代码,本文提供了解决方案,确保Set集合能够正确地被更新和持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    关于SharedPreferences中getStringSet无法改变Set的问题

     最近在做android项目的时候,遇到一个很常见的需求,就是在动态的将历史输入记录,在autocompletetextview中输入框自动提示补全,由于是动态的,故补全内容应该动态的从数据库中,或SharedPreferences中获取。然而就自然而然的想起了SharedPreferences中存在的putStringSet方法,但是在实际使用中遇到一个奇怪的问题,我每次成功输入之后都会讲输入记录存入Set中,更确切的说应该是追加入之前的Set集合中,那就免不了在调用putStringSet之前,需要先在初始化的时候getStringSet出我之前已存在的历史Set。之后,我就犯了如下错误

     HashSet<String> set=gettStringSet("History");

     set.add("ABC");//例如我输入了ABC

     set.add("123");

     ...

     ...

      set.add("789");

     putStringSet("History",set);

     我以为这样写就可以达到更新了SharedPreferences中,Key等于History的set集合。

  

public abstract SharedPreferences.Editor putStringSet (String key, Set<String> values)

Added in API level 11
Set a set of String values in the preferences editor, to be written back once commit() is called.

Parameters
key	The name of the preference to modify.
values	The new values for the preference.
Returns
Returns a reference to the same Editor object, so you can chain put calls together.


但是事实它并没有成功的保存到Set中。我通过查看/data/data/your_package目录下  SharedPreferences_自定义的名字.xml文件中,可以看到,并没有保存到之前我输入的ABC,123, ......789。 实在郁闷之后,翻看API。 我们可以清楚地看到API里提示,我们不能直接修改通过getStringSet方法调用的那个实例,即我们不能像刚才那样,直接在得到set之后,直接新增或删除set中数据,之后再put回去。

public abstract Set<String> getStringSet (String key, Set<String> defValues)

Added in API level 11
Retrieve a set of String values from the preferences.

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.

Parameters
key	The name of the preference to retrieve.
defValues	Values to return if this preference does not exist.
Returns
Returns the preference values if they exist, or defValues. Throws ClassCastException if there is a preference with this name that is not a Set.
Throws
ClassCastException	


 

所以介于以上方法,可以通过这样的方式更新Set

HashSet<String> set=gettStringSet("History");

     set.add("ABC");//例如我输入了ABC

     set.add("123");

     ...

     ...

      set.add("789");

 

HashSet<String> tepSet =new Hash<String>();

Iterator<String> iterator=set.iterator();

  if(iterator.hasNext()){

     tepSet.add(iterator.next());

   }   

     putStringSet("History",tepSet);

即可完成更新在sp中gengxinSet

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值