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?


当前回答

您可以将其转换为Map Object来存储它,然后在检索SharedPreferences时将值更改回ArrayList。

其他回答

我已经阅读了上面所有的答案。这都是正确的,但我找到了一个更简单的解决方案如下:

Saving String List in shared-preference>> public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) { SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit(); editor.putInt(pKey + "size", pData.size()); editor.commit(); for (int i = 0; i < pData.size(); i++) { SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit(); editor1.putString(pKey + i, (pData.get(i))); editor1.commit(); } } and for getting String List from Shared-preference>> public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) { int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0); List<String> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, "")); } return list; }

这里的常数。APP_PREFS是要打开的文件的名称;不能包含路径分隔符。

正如@nirav所说,最好的解决方案是使用Gson实用工具类将其作为json文本存储在sharedpreferences中。下面是示例代码:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();

我的utils类保存列表到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);
    }
}

使用

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

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

. 我的utils的完整代码//检查使用实例的活动代码

下面的代码是公认的答案,为新手(我)多写几行,例如。说明了如何将set类型对象转换回arrayList,并提供了关于`之前操作的附加指导。putStringSet'和。getstringset '。(谢谢你邪恶)

// shared preferences
   private SharedPreferences preferences;
   private SharedPreferences.Editor nsuserdefaults;

// setup persistent data
        preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
        nsuserdefaults = preferences.edit();

        arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
        //Retrieve followers from sharedPreferences
        Set<String> set = preferences.getStringSet("following", null);

        if (set == null) {
            // lazy instantiate array
            arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
        } else {
            // there is data from previous run
            arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
        }

// convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
                Set<String> set = new HashSet<String>();
                set.addAll(arrayOfMemberUrlsUserIsFollowing);
                nsuserdefaults.putStringSet("following", set);
                nsuserdefaults.commit();

对于String, int, boolean,最好的选择是sharedPreferences。

如果你想存储数组列表或任何复杂的数据。最好的选择是Paper library。

添加依赖关系

implementation 'io.paperdb:paperdb:2.6'

初始化文件

应该在Application.onCreate()中初始化一次:

Paper.init(context);

Save

List<Person> contacts = ...
Paper.book().write("contacts", contacts);

加载数据

如果对象在存储中不存在,请使用默认值。

List<Person> contacts = Paper.book().read("contacts", new ArrayList<>());

给你。

https://github.com/pilgr/Paper