如何写code键使共享preferences的数组中的android? [英] How can write code to make sharedpreferences for array in android?

查看:137
本文介绍了如何写code键使共享preferences的数组中的android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在机器人工作。我想打的共享preference在我的code,但我不知道由我可以做一个共享preference数组,以及如何可以使用该共享preference值在彼此的方式类。

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 use the value of that sharedpreference in another class.

这是循环我在一个阵列中: - 网址[I] = sitesList.getWebsite()得到(我);

This is my array in one for loop :- urls[i]=sitesList.getWebsite().get(i);

我想使这个网址[]数组的份额preference。请建议我,我怎么能写code申报的共享preference,我怎么能检索该共享preference价值呢?

i want to make share preference of this urls[] array. please suggest me how can i write code to declare sharedpreference and how can i retrieve value of that sharedpreference ?

感谢你在前进。

推荐答案

putStringSet getStringSet 仅在使用API 11。

putStringSet and getStringSet are only available in API 11.

另外,您可以使用JSON像这样序列化数组:

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

设置和retreive你的URL像这样:

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

这篇关于如何写code键使共享preferences的数组中的android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆