如何编写代码,以使android的数组共享首选项?

我在android工作。 我想在我的代码中使sharedpreference,但我不知道我可以做一个数组sharedpreference的方式,以及如何可以在另一个类中使用该sharedpreference的值。

这是我的数组在一个for循环: – urls [i] = sitesList.getWebsite()。get(i);

我想让这个urls []数组的共享偏好。 请build议我如何编写代码来声明sharedpreference以及如何检索该sharedpreference的值?

先谢谢你。

putStringSetgetStringSet仅在API 11中可用。

或者,你可以使用JSON序列化你的数组,像这样:

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

设置并检索您的url,如下所示:

 // 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();