In shared preferences how to store string array in android application

南笙酒味 提交于 2019-12-18 03:49:02

问题


In my application am using list view in base adapter.

when i click the item its id store in shared preferences string array format. how to save multiple item id in string array format [1,2,5,6] like this


回答1:


You can try using JSONArray as JSON is light-weight also, you can create a JSONArray and write it to SharedPreference as String.

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



回答2:


If you are using API 11 then its possible by using putStringSet. Otherwise you may either convert your string array into a single string as mentioned by @hotverispicy or use SQLite database




回答3:


you can save it as string by ,(comma) seperator and while fetching just use split()

string toPut="";

toPut += "listItem,";

set toPut in your SharePreference and commit()

To get the same in array: get prefString from SharePreference

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


来源:https://stackoverflow.com/questions/10241556/in-shared-preferences-how-to-store-string-array-in-android-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!