I have some instance fields in an Android activity that I initialize on onCreate, and then just use everywhere else within the activity.

But, sometimes (very rarely, once every few thousand uses) this instance field is null on onResume, leading to an immediate NullPointerException.

Here's a very simple working example:

class Foo {
}

class CrashingActivity extends Activity {
    private Foo foo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        foo = new Foo();
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.i("CrashingActivity", "Foo: " + foo); // CRASH!
    }
}

I don't think we need to use onPause or onSaveInstanceState, right?

Why is this crash happening?

没有正确的解决方案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top