开发者

Lost global variables in Android

I used a static class with static variables to access them from a lot of classes.

It works fine, but when application was some hours in background and I opened it, it cr开发者_JS百科ashes. To resolve this, I change the static class but another that extends Application.

For example, if I want to save an integer in the Application class:

public class MusicUtils extends Application {
    public  int tolerance = 0;
    public  int getTolerance() {
        return tolerance;
    }

    public  void setTolerance(int tolerance) {
        this.tolerance = tolerance;
    }
}

In class A I do: musicutils = (MusicUtils)getApplication(); musicutils.setTolerance(value_int);

And in class B I do: int value = musicutils.getTolerance();

Well, in class B, that works perfect. But, when I open this class some hours later, it crashes...

In Manifest I have:

<application android:icon="@drawable/app_music"
    android:label="@string/musicbrowserlabel"
    android:name="MusicUtils">

    (.......) Activities and more
</application>


What exception did you get? I never met this problem before, but I guess Android has free your application's memory, so when you resume the app'll crash. Try to save your value to SharedPreferences in onTerminal() of Application class, then restore it somewhere when you resume.


Try serializing your non-primitive objects into a file!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜