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?


当前回答

我的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的完整代码//检查使用实例的活动代码

其他回答

还有Kotlin:

fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
    putString(key, list?.joinToString(",") ?: "")
    return this
}

fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
    val value = getString(key, null)
    if (value.isNullOrBlank())
        return defValue
    return ArrayList (value.split(",").map { it.toInt() }) 
}

使用这个自定义类:

public class SharedPreferencesUtil {

    public static void pushStringList(SharedPreferences sharedPref, 
                                      List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref, 
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }
}

使用方法:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));

以防有人需要保存列表的列表,即list < list < String > >。我是这样做的:

序列化

Gson gson = new Gson();
// Save the size of the array
sharedPreferencesEditor.putInt("ArraySize", myArray.size());

for (int i=0; i<myArray.size(); i++) {
  String key = "Array"+i;
  String json = gson.toJson(myArray.get(i));
  sharedPreferencesEditor.putString(key, json);
}

sharedPreferencesEditor.commit();

反序列化

// Get the size of the array to be deserialized. In my case, the default number should be 3
int arraySize = sharedPreferences.getInt("ArraySize",3);

myArray = new ArrayList<List<String>>();

for (int i=0; i<arraySize; i++) {
  String key = "Array"+i;
  String json = sharedPreferences.getString(key, null);
  List<String> arrayTemp= gson.fromJson(json, List.class);
  myArray.add(arrayTemp);
}

// My array may also include components with empty strings. 
// Gson makes them null values and it is not possible 
// to deserialize them as empty strings. 
// The following takes care of that:

for (int i=0; i<myArray.size();i++) {
   if (myArray.get(i) == null) {
      List<String> emptyComponent = new ArrayList<String>() {
         { add(""); }
      };
      myArray.set(i,emptyComponent);
   }
}

Android sharedpreferences允许您将基本类型(Boolean, Float, Int, Long, String和StringSet,自API11以来可用)作为xml文件保存在内存中。

任何解决方案的关键思想都是将数据转换为这些基本类型之一。

我个人喜欢将my list转换为json格式,然后将其保存为SharedPreferences值中的字符串。

为了使用我的解决方案,你必须添加谷歌gsonlib。

在gradle中只需添加以下依赖项(请使用谷歌的最新版本):

compile 'com.google.code.gson:gson:2.6.2'

保存数据(HttpParam是你的对象):

List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);

editor.apply();

检索数据(HttpParam是你的对象):

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 

List<HttpParam> httpParamList =  
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
            }.getType());

以上答案都是正确的。:)我自己就用了其中一个。然而,当我读到这个问题时,我发现这篇文章实际上是在谈论一个不同的场景,如果我没有弄错的话。

"我需要这个数组一直存在即使用户离开了活动然后想要在稍后的时间回来"

实际上,他希望数据一直存储到应用程序打开为止,而不管用户在应用程序中更换屏幕。

“然而,我不需要阵列可用后,应用程序已完全关闭”

但是一旦应用程序关闭,数据就不应该被保存。因此,我觉得使用SharedPreferences并不是最优的方式。

对于这个需求,我们可以创建一个扩展Application类的类。

public class MyApp extends Application {

    //Pardon me for using global ;)

    private ArrayList<CustomObject> globalArray;

    public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
        globalArray = newArray; 
    }

    public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
        return globalArray;
    }

}

通过setter和getter,可以从应用程序中的任何地方访问ArrayList。最好的部分是一旦应用程序关闭,我们不必担心数据被存储。:)