将ArrayList保存到SharedPreferences

375

我有一个包含自定义对象的ArrayList,每个自定义对象都包含各种字符串和数字。即使用户离开活动并希望在以后的某个时间回来,我也需要保留这个数组,但是在完全关闭应用程序后,我不需要该数组可用。我通过使用SharedPreferences将许多其他对象保存在此方式中,但我无法弄清楚如何以此方式保存整个数组。这是可能的吗?也许SharedPreferences不是解决此问题的方法?是否有更简单的方法?


你可以在这里找到答案:https://dev59.com/4GUp5IYBdhLWcg3w3ad1#40237149 - Apurva Kolapkar
这是完整的示例,请访问以下网址:http://stackoverflow.com/a/41137562/4344659 - Sanjeev Sangral
如果有人正在寻找解决方案,这可能是你正在寻找的答案,其中包含Kotlin的完整使用示例。https://stackoverflow.com/a/56873719/3710341 - Sagar Chapagain
38个回答

0
    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();
        }
    }

0
Saving and retrieving the ArrayList From SharedPreference
 public static void addToPreference(String id,Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        ArrayList<String> list = getListFromPreference(context);
        if (!list.contains(id)) {
            list.add(id);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            Set<String> set = new HashSet<>();
            set.addAll(list);
            edit.putStringSet(Constant.LIST, set);
            edit.commit();

        }
    }
    public static ArrayList<String> getListFromPreference(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
        ArrayList<String> list = new ArrayList<>();
        if (set != null) {
            list = new ArrayList<>(set);
        }
        return list;
    }

这会保留顺序吗? - Brian Reinhold
我的理解是,'Set' 不保留顺序。LinkedHashSet 会保留。而 ShardePreferences 既不会恢复 LinkedHashSet,也无法将其转换为 LinkedHashSet。因此,我不确定会返回什么。 - Brian Reinhold

0

使用 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

0

使用SharedPreferences中的getStringSet和putStringSet非常简单,但在我的情况下,我必须在添加任何内容到Set之前复制Set对象。否则,如果我的应用程序被强制关闭,Set将不会被保存。可能是因为API下面的注释所述。(如果通过返回按钮关闭应用程序,则仍然保存)

请注意,您不得修改此调用返回的集合实例。如果您这样做,存储数据的一致性无法保证,您也无法修改实例。 http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();

Set<String> outSet = prefs.getStringSet("key", new HashSet<String>());
Set<String> workingSet = new HashSet<String>(outSet);
workingSet.add("Another String");

editor.putStringSet("key", workingSet);
editor.commit();

0
以上所有答案都是正确的。 :) 我自己也用了其中之一来解决我的问题。但是当我读到这个问题时,我发现 OP 实际上谈论的是与此帖子标题不同的情况,如果我没有理解错的话。

“我需要数组保留下来,即使用户离开活动,然后想在以后的某个时间回来”

他实际上希望数据在应用程序打开时保留,无论用户在应用程序中更改屏幕如何。

“但是,当应用程序完全关闭后,我不需要数组可用”

但是一旦应用程序关闭,数据就不应该被保存。因此,我认为使用 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。最好的部分是一旦应用程序关闭,我们就不必担心数据被存储。 :)


0
请使用以下两种方法在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)
}  

0
public static void WriteSharePrefrence1(Context context, String key, 
ArrayList<HashMap<String, String>> value)
{
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(value);
    editor.putString(key, json);
    editor.commit();
}
public static ArrayList<HashMap<String, String>> ReadSharePrefrence1(Context context, 
 String key)
{
    String data;
    Gson gson = new Gson();
    ArrayList<HashMap<String, String>> items = new ArrayList<>();
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences.Editor editor = preferences.edit();
    data = preferences.getString(key, "");

    Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {}.getType();
    items = gson.fromJson(data, type);

    return items;
}

-1
public class VcareSharedPreference {
  private static VcareSharedPreference sharePref = new VcareSharedPreference(); 
  private static SharedPreferences sharedPreferences; 
  private static SharedPreferences.Editor editor;
  private VcareSharedPreference() {
 } 
public static VcareSharedPreference getInstance(Context context) {
    if (sharedPreferences == null) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    return sharePref;
 }
public void save(String KEY, String text) {
    editor.putString(KEY, text);
    editor.commit();
}
 public String getValue(String PREFKEY) {
    String text;

    //settings = PreferenceManager.getDefaultSharedPreferences(context);
    text = sharedPreferences.getString(PREFKEY, null);
    return text;
}
public void removeValue(String KEY) {
    editor.remove(KEY);
    editor.commit();
}

public void clearAll() {
    editor.clear();
    editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
    Gson gson = new Gson();
    String json = gson.toJson(modelCourses);
    editor.putString(key, json);
    editor.apply();
}

public ArrayList<ModelWelcome> getArray(String key) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString(key, null);
    Type type = new TypeToken<ArrayList<ModelWelcome>>() {
    }.getType();
 return gson.fromJson(json, type);}}

这是用于保存任何值的SharedPreference单例类。谢谢。 - nithin joseph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接