Rare occurrence: Instance fields not initialized on onResume in an Android activity
-
08-10-2022 - |
Domanda
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?
Nessuna soluzione corretta
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow