应用关闭后,在Android中存储ArrayList

时间:2011-05-26 03:02:34

标签: android

我有一个字符串的ArrayList,我正在从中绘制一个ListView。在应用程序中,用户可以向ArrayList添加项目,从而导致项目显示在ListView上。当应用程序正在运行时,ArrayList会保留其项目,但在重新启动后(或应用程序停止的任何其他时间)项目将丢失。我已经阅读过有关内部,外部和SQLite存储的信息,但我无法使用内部存储或外部存储,而且我对SQLite一无所知,应用程序将在周五发布。是否有更好的储蓄实施?我附上了完整的代码副本,没有任何存储方法供审阅。

感谢。

http://www.mediafire.com/?tf8093g39jv0f61< - code

3 个答案:

答案 0 :(得分:5)

使用首选项实施来保存ArrayList<String>。在onPause方法中使用此:

ArrayList<String> tobesaved = getData(); // fetch the data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("SAVEDATA", new HashSet<String>(tobesaved));
edit.commit();

然后您可以使用onResume方法获取它:

ArrayList<String> retrieved = new ArrayList<String>(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getStringSet("SAVEDATA", new HashSet<String>()));
编辑:我没有机会查看你的代码:mediafire试图在我的浏览器上打开一些弹出窗口,所以我很快关闭了标签,但这对你有用。尝试并且可能使用gist(http://gist.github.com)或者pastebin(http://pastebin.com/)代替共享更长的代码序列。

答案 1 :(得分:1)

你可以参考Serializable的想法,参考以下链接,你可能会有一个想法

http://developer.android.com/reference/java/io/Serializable.html

http://www.jondev.net/articles/Android_Serialization_Example_%28Java%29

答案 2 :(得分:1)

ArrayList<String> tobesaved = getData(); // fetch the data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("SAVEDATA", new HashSet<String>(tobesaved));
edit.commit();

ArrayList<String> retrieved = new ArrayList<String>(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getStringSet("SAVEDATA", new HashSet<String>()));

此代码有效,但我的Arraylist按字母顺序排序。这个hashSet弄乱了我的字符串的字母组织。 。 。任何人都可以做出这个答案,非常棒吗?通过使ArrayList保存并加载相同的顺序??