首页 > 解决方案 > 在共享首选项中插入数组

问题描述

嘿家伙,我有一个我正在做的应用程序,它可以为电影加载 Android 电视视图。

我有一个网站,其中包含我的登录和内容数据库中的所有信息。

所以在leanback中,类别已经定义为:

public static final String MOVIE_CATEGORY[] = {
        "Category Zero",
        "Category One",
        "Category Two",
        "Category Three",
        "Category Four",
        "Category Five",
};

但我想从我的数据库中获取信息。

所以主要我创建了 AsyncHttpTask 任务并解析我的响应,我的目标是在我的共享首选项中插入类别并从 MOVIE_CATEGORY 中检索它。

我只需要身份证和姓名

   private void parseResult(String result) {

        try {
            JSONArray jsonarray = new JSONArray(result);

            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();

            for(int i=0; i < jsonarray.length(); i++) {
                JSONObject jsonobject = jsonarray.getJSONObject(i);
                String id       = jsonobject.getString("CID");
                String name    = jsonobject.getString("name");

 //Log.e("TAG","This is the results" + " ID "+ id + " Name "+name);
                iD = new String[]{id};
                catName=new String[]{name};
                editor.putString("id" + i, iD[i] + "name"+ catName[i] );
                editor.apply();
      Log.e("TAG","This is the results"  + Arrays.deepToString(iD));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

但我明白了

键:id0 值:6name2018

我的 json 响应如下所示:

    [{"CID":6,"name":"2018","image":"https:\/\/i.ytimg.com\/vi\/zTF913m8jVc\/maxresdefault.jpg"},
{"CID":7,"name":"2017","image":"http:\/\/mtltimes.ca\/wp-content\/uploads\/2017\/12\/Best-movies-2017-493x300.jpg"}

标签: androidarraysjson

解决方案


    /**
     * Set a set of String values in the preferences editor, to be written
     * back once {@link #commit} or {@link #apply} is called.
     * 
     * @param key The name of the preference to modify.
     * @param values The set of new values for the preference.  Passing {@code null}
     *    for this argument is equivalent to calling {@link #remove(String)} with
     *    this key.
     * @return Returns a reference to the same Editor object, so you can
     * chain put calls together.
     */
    Editor putStringSet(String key, @Nullable Set<String> values);


public static void storeSharedItem(Context ctx, String key, Set<String> stringSet) {
    SharedPreferences sharedPref = ctx.getSharedPreferences(
            Constants.WOK_SHARED_PREF, 0);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putStringSet(key, stringSet);
    editor.apply();
}

推荐阅读