How can write code to make sharedpreferences for array in android?

前端 未结 1 427
温柔的废话
温柔的废话 2020-11-27 15:30

I am working in android. I want to make sharedpreference in my code, but i dont know the way by which i can make a sharedpreference for array and how can us

相关标签:
1条回答
  • 2020-11-27 16:10

    putStringSet and getStringSet are only available in API 11.

    Alternatively you could serialize your arrays using JSON like so:

    public static void setStringArrayPref(Context context, String key, ArrayList<String> values) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray a = new JSONArray();
        for (int i = 0; i < values.size(); i++) {
            a.put(values.get(i));
        }
        if (!values.isEmpty()) {
            editor.putString(key, a.toString());
        } else {
            editor.putString(key, null);
        }
        editor.commit();
    }
    
    public static ArrayList<String> getStringArrayPref(Context context, String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String json = prefs.getString(key, null);
        ArrayList<String> urls = new ArrayList<String>();
        if (json != null) {
            try {
                JSONArray a = new JSONArray(json);
                for (int i = 0; i < a.length(); i++) {
                    String url = a.optString(i);
                    urls.add(url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }
    

    Set and retreive your URLs like so:

    // store preference
    ArrayList<String> list = new ArrayList<String>(Arrays.asList(urls));
    setStringArrayPref(this, "urls", list);
    
    // retrieve preference
    list = getStringArrayPref(this, "urls");
    urls = (String[]) list.toArray();
    
    0 讨论(0)
提交回复
热议问题