Application class variables gets uninitialised in android

这一生的挚爱 提交于 2019-12-24 05:47:08

问题


I have created an android app in which i'm using an application class to store and access the global variables. But i came across a strange behavior that all the variables in my application class gets uninitialized in the following scenarios,

  1. if my app is idle for sometime(say 10 minutes or so).
  2. if my app goes to background (if a browser gets opened above the app).

I searched a lot in SO and web and doesn't found any suitable answer. AFAIK once application class is initialized it will be accessible for the lifetime of the application. Am i missing something here?

Since i'm new to android development i may be doing something wrong here. Can anyone point me to the right direction?...Thanks in advance.

public class MyApp extends Application {

private MyClass classObj = new MyClass();
private boolean flagOne = true;
private boolean flagTwo = false;

void setFlagOne(boolean flag) {
    flagOne = flag;
}

boolean getFlagOne() {
    return flagOne;
}

void setFlagTwo(boolean flag) {
    flagTwo = flag;
}

boolean getFlagTwo() {
    return flagTwo;
}

void setMyClassObj(MyClass obj) {
    classObj = obj;
}

boolean getMyClassObj() {
    return classObj;
}
}

回答1:


At last i got it sorted out by saving the variable state using shared preferences and storing the object in application files directory. So if the application recreates at any time (sometimes if the app goes in background) i restore the state of the variables and read the object back. So the variables don't go uninitialised at an point of time.

Storing values,

SharedPreferences pref = getSharedPreferences("appstate", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("flagone", flagOne);
editor.putBoolean("flagtwo", flagTwo);

Retrieving values,

SharedPreferences pref = getSharedPreferences("appstate", Context.MODE_PRIVATE);
flagOne = pref.getBoolean("flagone", true);
flagTwo = pref.getBoolean("flagtwo", false);


来源:https://stackoverflow.com/questions/24060862/application-class-variables-gets-uninitialised-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!