Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1613
别跟我提以往
别跟我提以往 2020-11-22 11:27

I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences. How can I do?

NOTE:

相关标签:
11条回答
  • 2020-11-22 12:03

    Shared preferences introduced a getStringSet and putStringSet methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.

    Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:

    package com.example.utils;
    
    import org.json.JSONObject;
    import org.json.JSONArray;
    import org.json.JSONException;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    
    public class JSONSharedPreferences {
        private static final String PREFIX = "json";
    
        public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
            editor.commit();
        }
    
        public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
            editor.commit();
        }
    
        public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
        }
    
        public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
        }
    
        public static void remove(Context c, String prefName, String key) {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
                SharedPreferences.Editor editor = settings.edit();
                editor.remove(JSONSharedPreferences.PREFIX+key);
                editor.commit();
            }
        }
    }
    

    Now you can save any collection in shared preferences with this five methods. Working with JSONObject and JSONArray is very easy. You can use JSONArray (Collection copyFrom) public constructor to make a JSONArray out of any Java collection and use JSONArray's get methods to access the elements.

    There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.

    0 讨论(0)
  • 2020-11-22 12:03

    I loaded an array of waist sizes (already created in my array.xml) into my preferences.xml file with the code below. @array/pant_inch_size is the id of the entire array.

     <ListPreference 
     android:title="choosepantsize"
     android:summary="Choose Pant Size"
     android:key="pantSizePref" 
     android:defaultValue="34" 
     android:entries="@array/pant_inch_size"
     android:entryValues="@array/pant_inch_size" /> 
    

    This populated the menu with choices from the array. I set the default size as 34, so when the menu pops up, they see size 34 is pre-selected.

    0 讨论(0)
  • 2020-11-22 12:05

    So from the android developer site on Data Storage:

    User Preferences

    Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

    So I think it is okay since it is simply just key-value pairs which are persisted.

    To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:

    // my list of names, icon locations
    Map<String, String> nameIcons = new HashMap<String, String>();
    nameIcons.put("Noel", "/location/to/noel/icon.png");
    nameIcons.put("Bob", "another/location/to/bob/icon.png");
    nameIcons.put("another name", "last/location/icon.png");
    
    SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
    SharedPreferences.Editor keyValuesEditor = keyValues.edit();
    
    for (String s : nameIcons.keySet()) {
        // use the name as the key, and the icon as the value
        keyValuesEditor.putString(s, nameIcons.get(s));
    }
    keyValuesEditor.commit()
    

    You would do something similar to read the key-value pairs again. Let me know if this works.

    Update: If you're using API level 11 or later, there is a method to write out a String Set

    0 讨论(0)
  • 2020-11-22 12:08

    Easy mode for complex object storage with using Gson google library [1]

    public static void setComplexObject(Context ctx, ComplexObject obj){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj)); 
        editor.commit();
    }
    
    public static ComplexObject getComplexObject (Context ctx){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        String sobj = preferences.getString("COMPLEX_OBJECT", "");
        if(sobj.equals(""))return null;
        else return new Gson().fromJson(sobj, ComplexObject.class);
    }
    

    [1] http://code.google.com/p/google-gson/

    0 讨论(0)
  • 2020-11-22 12:11

    The Simple way is, to convert it to JSON String as below example:

    Gson gson = new Gson();
    String json = gson.toJson(myObj);
    

    Then store the string in the shared preferences. Once you need it just get string from shared preferences and convert back to JSONArray or JSONObject(as per your requirement.)

    0 讨论(0)
提交回复
热议问题