2016-11-21 6 views
0

mapLayoutonCreateに初期設定され、onDestroyにリリースされています。なぜmapLayoutnullの場合onNewIntentdispatchKeyEventAndroidアクティビティについてonDestroyの後にKeyEventを受け取ることはできますか?なぜmapLayoutがnullですか?


onNewIntentこれはスタックトレースである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) 

を持っています。

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 ... 

これは

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); 
    } 
} 

答えて

0

ので、プライベート静的MapLayout mapLayout私のコードです。 'MainActivity'に複数のインスタンスがある場合。 'MainActivity'のインスタンスが破棄されると、 'mapLayout'は 'null'になります。

したがって、 'MainActivity'を使用すると、 'mapLayout'を使用するとNullPointExceptionが発生します。

関連する問題