Android 在 ondestroy() 之前保存状态
我想保存一些值在用户终止活动之前的文件中。我应该在哪种方法中实现这个?
除了使用文件或 sql lite 之外,是否有一种方法可以存储复杂的数据,例如布局(已动态更改)?
“onDestroy() 注意:不要指望调用此方法来保存数据!”
Possible Duplicate:
Android: Saving a state during Android lifecycle
i want to save some values in a file before the user terminates the activity.In which method should i implement this?
Apart from using a file , or sql lite is there a way of storing complex data such as a layout (that has dynamically changed ) ?
"onDestroy() Note: do not count on this method being called as a place for saving data!"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
布局绑定到容纳它的 Activity 的上下文,因此您不想将完整的 View 对象保存到文件中,因为它附加到的 Activity 是无效的。
最简单的方法(取决于您要保存的数据量和类型)是使用 SharedPreferences 库。它是一个文件 I/O 包装器,使保存和检索数据变得非常简单。您可以在
onPause()
方法中保存特定的布局数据,并按照onResume()
中的规范重建布局。如果您需要的数据对于
SharedPreferences
来说太复杂,则必须保存它以使用其他保存方法(可在该链接中找到)。重建布局的过程将是相同的。Layouts are bound to the context of the Activity that holds it, so you do no want to save full
View
objects to files because the Activity that it's attached to is void.The easiest method (depending on the amount and type of data you want to save) is using the SharedPreferences library. It's a file I/O wrapper that makes saving and retrieving data pretty simple. You can save the specific layout data in the
onPause()
method, the rebuild the layout with the specifications inonResume()
.If the data you need is too complex for
SharedPreferences
, you'll have to save it to use other methods for saving (found in that link). The process for rebuilding the layouts will be the same.我会在 onPause 方法中调用您想要传递给包的所有内容。这里有一些关于 android 生命周期 的内容,为什么不尝试存储如果您想从文件加载,请在 csv 中添加内容。 (逗号分隔值)(尽管主要用于基于图块的游戏)
I would call all the stuff you want to pass to the bundle in your onPause method. Here is some stuff on the android lifecycle and why not try storing stuff in csv if you want to load from file. (comma seperated values) (althoughthat is mainly used for tile based games)
您可以使用
SharedPreferences
,请参阅doc ,以及这个教程来理解怎么做:)you can use
SharedPreferences
, refer the doc , and this tutorial to understand how to do it :)为什么不使用 SharedPreference 保存数据?以下是 Android 文档: http://developer.android.com /guide/topics/data/data-storage.html#pref
Why not save the data using a SharedPreference? Here are the android docs: http://developer.android.com/guide/topics/data/data-storage.html#pref