1

几周以来,我多次搜索了一种保存 4 个 String[] 数组的简单方法。我尝试将它们转换为 Set 并保存到 SharedPref,但似乎效果不佳。我也遇到过 outputStream,但我没有找到任何好的例子。

我想保存以下 4 件:

String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];

信息正在通过 Intents 从另一个活动传递给此活动。

请提供任何简单的建议以使这些内容在内部保存。

4

2 回答 2

1

您可以通过转换为带有逗号分隔值的字符串来保存这些数组,并将它们保存在共享首选项中。喜欢 :

private void putToSharedPref(String[] array, String key, Context context) {
    StringBuilder value = new StringBuilder("");
    for (String i : array) {
        value.append(i + ",");
    }
    SharedPreferences.Editor editor = PreferenceManager
            .getDefaultSharedPreferences(context).edit();
    editor.putString(key, value.toString());
    editor.commit();
}

private String[] getFromSharedPreference(String key, Context context) {
    String[] values = PreferenceManager
            .getDefaultSharedPreferences(context).getString(key, "")
            .split(",");
    return values;
}
于 2013-11-04T05:17:26.403 回答
1
JSONArray mJSONArray = new JSONArray(Arrays.asList(debtName));

JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "prefName", "prefKey", mJSONArray);

使用可以将您的数据保存为 JSON 数组。

public class JSONSharedPreferences {
    private static final String PREFIX = "json";

    public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
        editor.commit();
    }

    public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
        editor.commit();
    }

    public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
    }

    public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
    }

    public static void remove(Context c, String prefName, String key) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.remove(JSONSharedPreferences.PREFIX+key);
            editor.commit();
        }
    }

}
于 2013-11-04T06:43:34.817 回答