SharedPreferences storage is fetched in order

When the target uses SharedPreferences for historical data storage, it wants to make the storage order consistent with the retrieved data.

Encountered problems The way to think of when storing multiple data is a collection, so I use editor.putStringSet() to store it, but this stores a set collection, and the set collection has no order.

The editor has no other collection storage method. You can only find another way

use String 

Idea: Use the separator to practice each data into a long String storage, and then remove the separator when taking it out

 

public void writeHistory(String path) {
       if(TextUtils.isEmpty(path)){
         return;
      }
        SharedPreferences save = this.getSharedPreferences("save", MODE_PRIVATE);
        SharedPreferences.Editor editor = save.edit();
        String keywords = save.getString("keywords","");
        if(keywords!=""){
            //15 strings
            String[] key = keywords.split("_",15);
            if( key.length>14){
                //The 15th remove
                keywords =  keywords.replace(key[14],"");
            }
            // determine whether it is the same
            for (int i = 0; i < key.length; i++) {
                if(path.equals(key[i])){
                    keywords =  keywords.replace(path+"_","");
                }
            }
        }
        editor.putStringSet()
        // delimiter
        editor.putString("keywords",path+"_"+keywords);
        editor.putLong("keywords_bak", System.currentTimeMillis());
        editor.commit();
    }

 

In this way, our deposit is 444444_333333_222222_11111_

 

 

Take it out below

ArrayList<String> readHistory() {
        ArrayList<String> list = new ArrayList<>();
        SharedPreferences save = this.getSharedPreferences("save", MODE_PRIVATE);
        String keywords = save.getString("keywords",null);
        if (null != keywords){
            String[] key = keywords.split("_");
            for (int i = 0; i < key.length; i++) {
                list.add(key[i]);
            }
        }
        return list;
    }

When taking out, put them into arraylist one by one 

 

 

I'm just a novice, if it's wrong, please leave a message below!

thanks

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326569816&siteId=291194637