在Android中的SharedPreferences中存储数组的最有效方法是什么?

时间:2017-09-25 08:59:58

标签: android arraylist save sharedpreferences

我需要在不使用PrefserHawk之类的外部库的情况下将数组存储在共享首选项中。我试过并发现了很多问题。

所以我的搜索让我有了两种不同的方法:

  1. 使用集合:

    //Set the values
    Set<String> set = new HashSet<String>();
    set.addAll(listOfExistingScores);
    scoreEditor.putStringSet("key", set);
    scoreEditor.commit();
    
    //Retrieve the values
    Set<String> set = myScores.getStringSet("key", null);
    
  2. 使用字符串操作:

    //Set the values
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < playlists.length; i++) {
        sb.append(playlists[i]).append(",");
    }
    prefsEditor.putString(PLAYLISTS, sb.toString());
    
    //Retrieve the values
    String[] playlists = playlist.split(",");
    
  3. 问题:当商品的订单无关紧要且我有大量商品(比如&gt; 300)时,更有效的方法是什么?

2 个答案:

答案 0 :(得分:0)

最有效的方法是通过ObjectSeializer存储在字符串中。

striing会丢失数据的顺序,但ObjectSerializer会记住它。这是您可以使用的ObjectSerializer:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerializer {


public static String serialize(Serializable obj) throws IOException {
    if (obj == null) return "";
    try {
        ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
        objStream.writeObject(obj);
        objStream.close();
        return encodeBytes(serialObj.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static Object deserialize(String str) throws IOException {
    if (str == null || str.length() == 0) return null;
    try {
        ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
        ObjectInputStream objStream = new ObjectInputStream(serialObj);
        return objStream.readObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static String encodeBytes(byte[] bytes) {
    StringBuffer strBuf = new StringBuffer();

    for (int i = 0; i < bytes.length; i++) {
        strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
        strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
    }

    return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length(); i+=2) {
        char c = str.charAt(i);
        bytes[i/2] = (byte) ((c - 'a') << 4);
        c = str.charAt(i+1);
        bytes[i/2] += (c - 'a');
    }
    return bytes;
}

}

并致电:

sharedpref.putString("data",ObjectSerializer.serialize(array1));

答案 1 :(得分:0)

JsonArray可帮助您转换和存储

public static void putStringArray(Context context, String key, String[] array) {
    if (context == null) {
        return;
    }
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    JSONArray mJSONArray = new JSONArray(Arrays.asList(array));
    editor.putString(key, String.valueOf(mJSONArray));
    editor.apply();
}

public static String[] getStringArray(String key, Context context) {
    if (context == null) {
        return null;
    }
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    String[] stringArray = new String[0];
    try {
        JSONArray jsonArray = new JSONArray(prefs.getString(key, ""));
        int len = jsonArray.length();
        stringArray = new String[len];

        for (int i = 0; i < len; i++) {
            try {
                stringArray[i] = jsonArray.getString(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return stringArray;
}