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?


当前回答

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

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是要打开的文件的名称;不能包含路径分隔符。

其他回答

请在kotlin中使用这两种方法将数据存储在ArrayList中

fun setDataInArrayList(list: ArrayList<ShopReisterRequest>, key: String, context: Context) {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val editor = prefs.edit()
    val gson = Gson()
    val json = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()   
}

fun getDataInArrayList(key: String, context: Context): ArrayList<ShopReisterRequest> {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val gson = Gson()
    val json = prefs.getString(key, null)
    val type = object : TypeToken<ArrayList<ShopReisterRequest>>() {

    }.type
    return gson.fromJson<ArrayList<ShopReisterRequest>>(json, type)
}  

使用这个对象——> TinyDB——Android-Shared-Preferences-Turbo非常简单。

TinyDB tinydb = new TinyDB(context);

tinydb.putList("MyUsers", mUsersArray);

得到

tinydb.getList("MyUsers");

更新

一些有用的例子和故障排除可以在这里找到:Android共享偏好TinyDB putListObject函数

你可以使用Gson库保存字符串和自定义数组列表。

首先你需要创建一个函数来保存数组列表到SharedPreferences。

public void saveListInLocal(ArrayList<String> list, String key) {

        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!

    }

你需要创建一个函数来从SharedPreferences获取数组列表。

public ArrayList<String> getListFromLocal(String key)
{
    SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);

}

如何调用保存和检索数组列表函数。

ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());

不要忘记在你的应用级别build.gradle中添加gson库。

实现“com.google.code.gson: gson: 2.8.2”

使用Kotlin,对于简单的数组和列表,你可以这样做:

class MyPrefs(context: Context) {
    val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
    var listOfFloats: List<Float>
        get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
        set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}

然后轻松访问首选项:

MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats
    public  void saveUserName(Context con,String username)
    {
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            usernameEditor = usernameSharedPreferences.edit();
            usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
            int size=USERNAME.size();//USERNAME is arrayList
            usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
            usernameEditor.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public void loadUserName(Context con)
    {  
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
            USERNAME.clear();
            for(int i=0;i<size;i++)
            { 
                String username1="";
                username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
                USERNAME.add(username1);
            }
            usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
            username.setAdapter(usernameArrayAdapter);
            username.setThreshold(0);

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }