将阵列保存到内部设备

时间:2013-11-04 04:34:11

标签: java android arrays outputstream

我已经多次搜索了几周,以便以简单的方式保存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从另一个传递给此活动。

请提供任何有关内部保存的简单建议。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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();
        }
    }

}