Domanda

In my app I store some data in the Application class:

public HashMap<String, HashMap<String, String>> getConfigs() {
    if (mConfigs != null) {
        return mConfigs;
    }
}

public void setConfigs(HashMap<String, HashMap<String, String>> configs) {
    mConfigs = configs;
}

Then I call it from an Activity for further use:

public String getValueByTag(String tag){
    return MyApplication.getInstance().getValueByTag(tag);
}

When I press the home button and run it later (i.e. after 1 hour), it crashes with a NullPointerException.

I know that the Android OS automatically kills the application if it is not used for a while, but what should I do to handle this problem?

È stato utile?

Soluzione

Store your data in SharedPreferences or in DB. You can also put them into JSONObject and store them in a form of file in your app folder. You would have to do such serialization each time setConfigs is called, or in your activity onPause. In Application.onCreate, you would restore your mConfigs .

Altri suggerimenti

Copied for this link.

Don't rely on static data members or custom Application subclass instances. There are many scenarios in which your process will be terminated and those values go away. They should be used for an in-memory cache of persistent content, and little else.

In Android System, as you said in the question, the process may be killed by the system manager. But as I knew, you can let your mConfigs to a static variable which will NOT be GC. In Dalvik, the class will NOT be unloaded even if it will NOT be used.

But if your process had been killed, you should reload your mConfigs in your Activity.onCreate.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top