In the general settings for storing an array of strings in an android application

In my application, I use the list view in the base adapter.

when I click an element stored in its identifier store in the format of string arrays of common preferences. how to save multiple element identifier in string array format [1,2,5,6] like this ....

thanks in advance...

+3
source share
3 answers

You can try to use it JSONArray, since JSON is also light-weight, you can create JSONArrayand write it to SharedPreference as a 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();
        }
+10
source

API 11, putStringSet. , @hotverispicy, SQLite

+4

you can save it as a string using ,(comma) seperator, and when fetching usesplit()

string toPut="";

toPut += "listItem,";

set toPut to SharePreferenceand commit ()

To get the same in an array: get prefString from SharePreference

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

All Articles