开发者

Application + Activity + onResume == NULL POINTER EXCEPTION

开发者 https://www.devze.com 2023-03-20 19:13 出处:网络
So I am having problem I just can\'t get my head around in Android. My program uses the Application class for storing globals.

So I am having problem I just can't get my head around in Android.

My program uses the Application class for storing globals.

In there I have the following

public ExampleClass SetOfExamples[];

@Override
public void onCreate() {
    super.onCreate();
    _appCtrl = this;
    SetOfExamples = new ExampleClass[10];
    // ARRAY IS INITED HERE - all entrys are setup.
}

then in an activity I have

protected void onResume() {
    super.onResume();
    appState = ((MyApplication)this.getApplication());    
    if(appState!=null)
    {
        if(appState.SetOfExamples[1]!=null)
        {
            // Do stuff
        }
        else
        {开发者_开发知识库
            // What do I do ???
        }
    }

}

Quite often in a deployed app (but never can reproduce myself!!!), it is falling into the "What do I do" portion of the code.

So why is this ? , how can my activity be resumed before myapplication create is called ? Or is the array being created by myapplication being deallocated ? , if so how to do I prevent that - I thought it was supposed to stay there as it's part of the global application context.

ADDITIONAL INFO: This activity IS the launch activity.


You shouldn't be comparing the element [1] to null because your entire array could be null, trying to access a part of a null array will cause the exception


Too long for comment - but could be a useful answer I guess so here goes:

My problem is I have a load of data that is intialized only once in the splashscreen. I got round it by setting a boolean flag in my application which I could use to check to know for sure that my application object was populated with data. In the onCreate or onResume of all of my activities I first check this flag, if it is false then I know I have a duff application object so I just finish all of my activities till i'm at the start of my activity stack then launch my splashscreen intent - to the user it just feels like a restart. No more mystery null pointers! I'm sure there is a more elegant solution (I believe we should be persisting data to disk in the onPause - not just relying on the application object staying alive).

Worked for me - hope this can help others.

0

精彩评论

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