简体   繁体   English

使用静态常量保存Android应用程序状态

[英]Saving Android Application State Using Static Constants

In my Android application I have used a Constants class to store app data like login user information using static variables. 在我的Android应用程序中,我使用了Constants类来使用静态变量存储应用程序数据,例如登录用户信息。 I'm able to use that data throughout the app. 我可以在整个应用程序中使用这些数据。 But, when I leave my app in background for a long time and start it later, it crashes. 但是,当我将应用长时间置于后台并稍后启动时,它崩溃了。 The error stack contains a NullPointerException on the variable that I have referenced from Constants class. 错误堆栈包含我从Constants类引用的变量上的NullPointerException。

When your application is cleared from memory, all static variables (which are obviously stored in memory) are cleared as well. 从内存中清除应用程序时,所有静态变量(显然存储在内存中)也会被清除。 The Saving Data Training details many of the available solutions to store data so that it can be properly restored even if the application is killed. 保存数据培训”详细介绍了许多可用的解决方案来存储数据,以便即使应用程序被终止也可以正确还原。 Simple key-value pairs can be stored in Shared Preferences . 简单的键/值对可以存储在Shared Preferences中

From static or any variables you couldn't retrieve the last changes after the application is shutdown. 在应用程序关闭后,您无法从静态变量或任何变量中检索最近的更改。 For that you need to save the values into file system or any lightweight databases(for example SQLite). 为此,您需要将值保存到文件系统或任何轻量级数据库(例如SQLite)中。 Whenever you start you application you need to load into your static fields from the file or database. 无论何时启动应用程序,都需要从文件或数据库加载到静态字段中。

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

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