保存ArrayList(android)

时间:2014-04-16 17:50:40

标签: android sharedpreferences

我的应用程序基本上是一个向人们展示世界标志的测验。我想添加一个保存功能,将当前标志添加到单独的列表中。现在,这是我点击"保存"按钮:

saveListGC.add(playList.get(1));

(playList.get(1)是当前标志)。问题是,我必须在每次脚本启动时重新定义saveListGC,并清空内容:

public static ArrayList<String> saveListGC = new ArrayList<String>();

所以我想知道的是如何保存这些数据,并在以后重新加载?我已经看过使用SharedPrefernces的事情,但我不太了解它。如果有人能够尽可能轻松地解释它,我会非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个如何使用SharedPreferences的简单示例:

    //intiat your shared pref
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    Editor editor = pref.edit();

    //store data to pref
    editor.putString("myString", "value 1");
    editor.commit();

    //retrieve data from pref
    String myString = pref.getString("myString", null);

但真正的问题是SharedPreferences不能存储List类型的Object(ArrayList),但是你可以使用这个方法存储Set类型的Object(比如Hashset)

Set<String> mySet = new HashSet<String>(); 
mySet.add("value1");
mySet.add("value2");
mySet.add("value3");

editor.putStringSet("MySet", mySet);

所以回答你的第二个问题,我建议你这样做:

//This is your List
ArrayList<String> saveListGC = new ArrayList<String>();

//Convert your List to a Set
Set<String> saveSetGC = new HashSet<String>(saveListGC);

//Now Store Data to the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
Editor editor = pref.edit();
editor.putStringSet("MySet", saveSetGC);
editor.commit();

//After that in another place or in another Activity , Or every where in your app you can Retreive your List back
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Set<String> mySetBack = pref.getStringSet("MySet", null);
//Convert Your Set to List again
ArrayList<String> myListBack = new ArrayList<String>(mySetBack);

//Here you can se the List as you like...............
Log.i("MyTag", myListBack.get(0));
Log.i("MyTag", myListBack.get(1));

祝你好运:)