在共享首选项中如何在android应用程序中存储字符串数组

Mur*_*san 3 android sharedpreferences

在我的应用程序中使用基本适配器中的列表视图.

当我点击该项时,其id存储在共享首选项字符串数组格式中.如何以字符串数组格式[1,2,5,6]这样保存多个项目ID ....

提前致谢...

Lal*_*ani 10

您可以尝试使用JSONArrayJSON light-weight,也可以创建一个JSONArray并将其作为String写入SharedPreference.

来写,

       SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(1);
        jsonArray.put(2);
        Editor editor = prefs.edit();
        editor.putString("key", jsonArray.toString());
        System.out.println(jsonArray.toString());
        editor.commit();
Run Code Online (Sandbox Code Playgroud)

阅读,

        try {
            JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
            for (int i = 0; i < jsonArray2.length(); i++) {
                 Log.d("your JSON Array", jsonArray2.getInt(i)+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)