【问题标题】:What is the most efficient way to store an array in SharedPreferences in Android?在 Android 的 SharedPreferences 中存储数组的最有效方法是什么?
【发布时间】:2018-03-06 04:39:05
【问题描述】:

我需要在共享首选项中存储一个数组,而不使用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(",");
    

问题:当物品的顺序无关紧要并且我有大量物品(例如 > 300)时,什么是更有效的方法?

【问题讨论】:

  • 你为什么不使用数据库?我通常不会对超过 30 个键使用 SharedPreferences
  • @gmetax,你是对的,通常情况下,我也是这样做的。但在这种情况下,这是我唯一需要存储的东西,我不想仅仅为一个 ArrayList 搞乱数据库实现。
  • 我找不到 SharedPreferences 的限制存储,但我认为在 SharedPreferences 上存储超过 1000 个值不是一个好习惯
  • @EmilAdz,这不是一个有效的解决方案,这只是做你的事情的一种方式。即使在 SharedPreferences 中存储这么多数据也永远不会有效。

标签: android arraylist save sharedpreferences


【解决方案1】:

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

字符串会丢失数据的顺序,但 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));

【讨论】:

  • 为什么使用字符串会丢失顺序?您正在按顺序在数组上运行并按顺序附加项目,拆分并保存附加项目的顺序。
【解决方案2】:

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;
}

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2010-09-24
    • 1970-01-01
    • 2017-01-12
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多