实例变量越来越设置为空,如果活动是由OS重建 [英] Instance variable getting set to null if activity is recreated by OS
问题描述
我一直在努力奋斗着这个问题相当长的一段时间了。
I have been struggling with this problem for quite some time now.
实例我的主要活动变量越来越设置,如果我一整天后启动的应用程序为null。所以,我的用户隔日应用程序崩溃一次,然后重新启动就好了。我假设的活动就会被杀死,并重新创建,当他们启动应用程序的第二天。
Instance variables of my main activity are getting set to null if I start app after a day. So, for my users every other day app crashes once and then restarts just fine. I am assuming that the activity gets killed and recreated and when they start app the next day.
基本上,可能会发生是由于onsavedinstance的意见得到重建,但这些观点需要的数据尚未公布,因为我不存储数据包。
Basically, what may be happening is due to "onsavedinstance" the views are getting recreated, but the data that those views need is not yet available as I do not store the data in the bundle.
如何prevent呢?我不倾向于存储每个变量包,因为它是一个不好的设计。什么是做到这一点的最好方法是什么?
How can I prevent it? I am not inclined towards storing each and every variable in bundle as it's a bad design. What's the best way to do it?
下面是我的code:
基本上我试图从服务器上填充的onCreate我的引导数据(dataWrapper)。我用在以后的code这个数据对象。一切工作正常,在第一次应用程序启动。但是,当用户经过一天或7-8小时打开的应用程序,对象dataWrapper原来是空。
Basically i am trying to populate my bootstrap data (dataWrapper) from server on "onCreate". I use this data object in subsequent code. All works fine on first app launch. But when user opens app after a day or 7-8 hours, the object "dataWrapper" turns out to be null.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//other initialization code
getData();
//remaining code
}
protected DataWrapper dataWrapper;
private void getData(){
try {
//url for fetching data
String url = "http://....."
new FetchAndPopulateMarketDataAsyncTask(this){
@Override public void onPostExecute(DataWrapper result)
{
if(result==null){
//server or no internet error
}
else{
dataWrapper = (DataWrapper)result;
}
}
}.execute(new URL(url));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
谢谢, 罗尼
Thanks, Rony
推荐答案
Android将杀死或根据需要释放的后台应用程序的内存。所以,你需要保持你的应用程序的状态,当它进入后台。
Android will kill or release memory of background applications as needed. So, you need to maintain state of your application when it goes into the background.
尝试重写双方的onSaveInstanceState和onRestoreInstanceState保存和恢复这些实例变量的值。
Try overriding both onSaveInstanceState and onRestoreInstanceState to save and restore the values of these instance variables.
这篇关于实例变量越来越设置为空,如果活动是由OS重建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!