diff --git a/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java b/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java index 673ce77..02038b3 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java @@ -480,7 +480,7 @@ public void manuallyLayoutChildren(View view) { } private void sendCommandToReactNative(String functionName, Object args) { - if (navViewFragment.requireActivity() != null && reactContext != null) { + if (hasValidFragment()) { CatalystInstance catalystInstance = reactContext.getCatalystInstance(); WritableNativeArray params = new WritableNativeArray(); if (args != null) { @@ -492,7 +492,7 @@ private void sendCommandToReactNative(String functionName, Object args) { @Override public void onArrival(ArrivalEvent event) { - if (navViewFragment.requireActivity() != null && reactContext != null) { + if (hasValidFragment()) { CatalystInstance catalystInstance = reactContext.getCatalystInstance(); WritableMap map = Arguments.createMap(); @@ -608,7 +608,7 @@ public String getNavSDKVersion() { @Override public void onTurnByTurn(NavInfo navInfo) { - if (navViewFragment.requireActivity() != null && reactContext != null) { + if (hasValidFragment()) { CatalystInstance catalystInstance = reactContext.getCatalystInstance(); WritableMap map = Arguments.createMap(); @@ -714,4 +714,17 @@ public void onMarkerInfoWindowTapped(Marker marker) { NavViewFragment getNavViewFragment() { return navViewFragment; } + + /** + * Helper method to check if the fragment is added and the reactContext is not null. + * requireActivity throws an exception if the fragment is not added or the activity is null, + * in this case exception is caught and false is returned. + */ + private boolean hasValidFragment() { + try { + return navViewFragment.isAdded() && navViewFragment.requireActivity() != null && reactContext != null; + } catch (Exception e) { + return false; + } + } }