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

来源:互联网 发布:法兰克编程教学 编辑:程序博客网 时间:2024/05/16 04:31

    关于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 11Set a set of String values in the preferences editor, to be written back once commit() is called.ParameterskeyThe name of the preference to modify.valuesThe new values for the preference.ReturnsReturns 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 11Retrieve 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.ParameterskeyThe name of the preference to retrieve.defValuesValues to return if this preference does not exist.ReturnsReturns the preference values if they exist, or defValues. Throws ClassCastException if there is a preference with this name that is not a Set.ThrowsClassCastException


 

所以介于以上方法,可以通过这样的方式更新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

0 0
原创粉丝点击