larno peng larno peng - 1 year ago 65
Android Question

Can receive KeyEvent after onDestroy called about Android Activity? Why mapLayout is null?

mapLayout
is init at
onCreate
and release at
onDestroy
. Why
mapLayout
is
null
when
onNewIntent
and
dispatchKeyEvent
?




onNewIntent
have
NullPointException


java.lang.NullPointerException: Attempt to invoke virtual method 'void MapLayout.clearFocusedOverlay()' on a null object reference
at com.xxx.activity.MainActivity.onNewIntent(MainActivity.java:486)
at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1210)
at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2438)





This is stackTrace.

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean MapLayout.hasFocusedOverlay()' on a null object reference
at com.xxx.activity.MainActivity.dispatchKeyEvent(MainActivity.java:794)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2389)
at ...





This is my code

public class MainActivity extends Activity {

private static MapLayout mapLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapLayout = (MapLayout) findViewById(R.id.map_container);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
mapLayout.clearFocusedOverlay()
}
@Override
protected void onDestroy() {
Log.i(TAG, "onDestroy");
mapLayout = null;
super.onDestroy();
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.i(TAG, "dispatchKeyEvent: "+event);
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (mapLayout.hasFocusedOverlay()) {
mapLayout.clearFocusedOverlay();
mapLayout.mapView.invalidate();
} else {
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
return true;
}
return super.dispatchKeyEvent(event);
}
}

Answer Source

Because private static MapLayout mapLayout; When 'MainActivity' have more than one instance. If one instance of 'MainActivity' destroy, the 'mapLayout' become to 'null'.

So when other instance of 'MainActivity' use 'mapLayout' will cause NullPointException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download