【问题标题】:Store ArrayList in Android after app closes应用关闭后在 Android 中存储 ArrayList
【发布时间】:2011-05-26 03:02:33
【问题描述】:

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

谢谢。

http://www.mediafire.com/?tf8093g39jv0f61

【问题讨论】:

  • 尝试在 paste 或 pastebin 上发布您的代码。

标签: android


【解决方案1】:

使用首选项实现保存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/)来共享更长的代码序列。

【讨论】:

  • 我不认为首选项管理器是用来存储大量信息的。
  • 他从未说过他要存储大量信息。他说他有一个字符串数组列表要存储。
  • 抱歉,我想起了 2008 年的 MediaFire,当时它实际上还不错。现在我每隔一秒就能赢得免费的 iPad 2。
  • 哈哈。你见过真正赢过的人吗?
  • 是的!不过,他不得不掏出 500 美元。
【解决方案2】:

【讨论】:

  • 是的,我想就是这样!谢谢。
【解决方案3】:
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以相同的顺序保存和加载??

【讨论】:

  • 在检索到的数组列表上使用collections.sort
猜你喜欢
  • 2014-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2015-02-22
相关资源
最近更新 更多