简体   繁体   English

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

[英]In shared preferences how to store string array in android application

In my application am using list view in base adapter. 在我的应用程序中使用基本适配器中的列表视图。

when i click the item its id store in shared preferences string array format. 当我点击该项时,其id存储在共享首选项字符串数组格式中。 how to save multiple item id in string array format [1,2,5,6] like this 如何以字符串数组格式[1,2,5,6]这样保存多个项目ID

You can try using JSONArray as JSON is light-weight also, you can create a JSONArray and write it to SharedPreference as String. 您可以尝试使用JSONArray因为JSON也很light-weight ,您可以创建一个JSONArray并将其作为String写入SharedPreference。

To write, 来写,

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

To Read, 读书,

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

If you are using API 11 then its possible by using putStringSet . 如果您使用的是API 11,则可以使用putStringSet Otherwise you may either convert your string array into a single string as mentioned by @hotverispicy or use SQLite database 否则,您可以将字符串数组转换为@hotverispicy提到的单个字符串,也可以使用SQLite数据库

you can save it as string by , (comma) seperator and while fetching just use split() 你可以将它保存为字符串, (逗号)分隔符,并在获取时使用split()

string toPut="";

toPut += "listItem,";

set toPut in your SharePreference and commit() 在您设置toPut SharePreference并提交()

To get the same in array: get prefString from SharePreference 要获得相同的阵列:得到prefString SharePreference

String[] fetchArray= prefString.split(",");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM