简体   繁体   English

如何在没有数据库以及Android中没有共享首选项的情况下永久保存arrayList?

[英]How can I save an arrayList permanently without database as well as without Shared preferences in Android?

I have an ArrayList with custom objects. 我有一个带有自定义对象的ArrayList。 Each custom object contains a variety of strings and numbers. 每个自定义对象均包含各种字符串和数字。 I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. 即使用户离开活动然后想要稍后再回来,我也需要阵列保持住状态,但是在应用程序完全关闭后,我不需要阵列可用。 I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. 我通过使用SharedPreferences以这种方式保存了许多其他对象,但是我不知道如何以这种方式保存我的整个数组。 Is this possible? 这可能吗? Maybe SharedPreferences isn't the way to go about this? 也许不是SharedPreferences可以解决这个问题? Is there a simpler method? 有没有更简单的方法?

You can serialize the ArrayList using ObjectInputStream and ObjectOutputStream since all your object appear to be serializable. 您可以使用ObjectInputStreamObjectOutputStream序列化ArrayList ,因为所有对象似乎都是可序列化的。

Serialization is described here : http://java.sun.com/developer/technicalArticles/Programming/serialization/ 序列化的描述如下: http : //java.sun.com/developer/technicalArticles/Programming/serialization/

In Android, the recommended place to save such files is to use the directory specified by Context.getCacheDir() so, on your Activity you simply call this.getCacheDir() to get it and then build a unique file name you feed to the ObjectStream objects. 在Android中,建议保存此类文件的地方是使用Context.getCacheDir()指定的目录,因此,在您的Activity上,只需调用this.getCacheDir()即可获取它,然后构建一个唯一的文件名,并将其输入给ObjectStream对象。

If you don't need it after the application is killed maybe you can try using onSaveInstanceState() and onRestoreInstanceState() . 如果在应用程序被终止后不需要它,则可以尝试使用onSaveInstanceState()onRestoreInstanceState()

Here is a short example showing how to use it! 是一个简短的示例,展示了如何使用它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM