Save ArrayList to SharedPreferences

2018-12-31 00:07发布

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?

30条回答
君临天下
2楼-- · 2018-12-31 00:54

My utils class for save list to SharedPreferences

public class SharedPrefApi {
    private SharedPreferences sharedPreferences;
    private Gson gson;

    public SharedPrefApi(Context context, Gson gson) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = gson;
    } 

    ...

    public <T> void putList(String key, List<T> list) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, gson.toJson(list));
        editor.apply();
    }

    public <T> List<T> getList(String key, Class<T> clazz) {
        Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
        return gson.fromJson(getString(key, null), typeOfT);
    }
}

Using

// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);

// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);

.
Full code of my utils // check using example in Activity code

查看更多
浪荡孟婆
3楼-- · 2018-12-31 00:56

Saving Array in SharedPreferences:

public static boolean saveArray()
{
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor mEdit1 = sp.edit();
    /* sKey is an array */
    mEdit1.putInt("Status_size", sKey.size());  

    for(int i=0;i<sKey.size();i++)  
    {
        mEdit1.remove("Status_" + i);
        mEdit1.putString("Status_" + i, sKey.get(i));  
    }

    return mEdit1.commit();     
}

Loading Array Data from SharedPreferences

public static void loadArray(Context mContext)
{  
    SharedPreferences mSharedPreference1 =   PreferenceManager.getDefaultSharedPreferences(mContext);
    sKey.clear();
    int size = mSharedPreference1.getInt("Status_size", 0);  

    for(int i=0;i<size;i++) 
    {
     sKey.add(mSharedPreference1.getString("Status_" + i, null));
    }

}
查看更多
怪性笑人.
4楼-- · 2018-12-31 00:59

You can also convert the arraylist into a String and save that in preference

private String convertToString(ArrayList<String> list) {

            StringBuilder sb = new StringBuilder();
            String delim = "";
            for (String s : list)
            {
                sb.append(delim);
                sb.append(s);;
                delim = ",";
            }
            return sb.toString();
        }

private ArrayList<String> convertToArray(String string) {

            ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
            return list;
        }

You can save the Arraylist after converting it to string using convertToString method and retrieve the string and convert it to array using convertToArray

After API 11 you can save set directly to SharedPreferences though !!! :)

查看更多
其实,你不懂
5楼-- · 2018-12-31 00:59

don't forget to implement Serializable:

Class dataBean implements Serializable{
 public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();

https://stackoverflow.com/a/7635154/4639974

查看更多
情到深处是孤独
6楼-- · 2018-12-31 01:00

best way is that convert to JSOn string using GSON and save this string to SharedPreference. I also use this way to cache responses.

查看更多
荒废的爱情
7楼-- · 2018-12-31 01:00

You can convert it to a Map Object to store it, then change the values back to an ArrayList when you retrieve the SharedPreferences.

查看更多
登录 后发表回答