美文网首页
使用SharedPreferences本地缓存List数据

使用SharedPreferences本地缓存List数据

作者: wt龙 | 来源:发表于2016-10-21 15:17 被阅读82次

今天的需求是在选择城市列表中加入一个最近访问城市的模块,
当然,首先想到的就是SharedPreferences来本地缓存数据,然后,找了一下put方法,并没有找到缓存arraylist的方法。这。。。

思考一番:

在缓存本地登录状态的类中写了两个方法;


/*  
* 在存数据和拿数据的时候,我们传入key值一定要相同。
* 缓存数据的同时。我们会缓存传入的list的size。来递增key值。
* 在我们拿数据的时候。要先得到之前缓存的数据的size(默认为0),来递增key值,以便取出数据。。** */
public void putList(Context context ,String key,List<String> strList){   
   if(strList .size() ==0)  
          return;    
  //将list的数量存储起来    
  editor.putInt("listsize",strList.size());
      editor.commit(); 
     //存储list中的数据   
   for(int i =0;i<strList.size();i++){     
       editor.putString(key+i,strList.get(i).toString());  
          editor.commit(); 
     }}

public  List<String>  getList(Context context,String key){
      List<String>  strlist = new ArrayList();    
  //取出存储的list数量  
  int size = sharedPreferences.getInt("listsize",0);
      //根据list的数据取出   
   for(int i =0 ;i<size;i++){ 
           String s =sharedPreferences.getString(key+i,"");     
       strlist.add(s);  
    }   
   return strlist;}
  • 1.每次进入选择城市界面。先从缓存中拿到数据存放到一个list中。
  • 然后判断如果拿到的数据时空的话,默认add一个数据
  • 2.在用户选择城市的时候。
  • 先判断我们取出的数据中有没有用户选择的数据(list.contains()方法),如果有,不执行操作,否则,在list中add用户选择的城市。
  • 我们的最近访问城市最多为9个,如果我们从缓存中取出的list的size ==9的话,remove list的第0条,然后在存入用户选择的数据。

相关文章

网友评论

      本文标题:使用SharedPreferences本地缓存List数据

      本文链接:https://www.haomeiwen.com/subject/bcccuttx.html