Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top