Im a little bit confused in Android Studio. I didint seen this kind of errors in Eclipse before.
Example:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction tf = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(AddDialogFragment.TAG);
this code is working fine, but fragmentManager.beginTransaction(); gets highlighted and says: Method invocation 'fragmentManager.beginTransaction' may produce 'java.lang.NullPointerException' less... (Ctrl+F1)
This inspection reports those conditions in the specified inspection scope that are always true or false, as well as points out where a RuntimeException may be thrown, based on data flow analysis of the code. This inspection also reports Nullable/NotNull contract violations. Annotations to support the contract can be configured (by default @Nullable/@NotNull annotations from annotations.jar will be used)
Do i have to check for Null before?
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager != null)
FragmentTransaction tf = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(AddDialogFragment.TAG);
I have never seen this in any Tut or Example before. If this is a stupid question than sorry, but im still a beginner :) .
From what I've seen, Android Studio shows a bit too much warnings about potential NullPointerExceptions
, even for methods that will never return null. I simply ignore some of them, but it's useful to carefully check all of them, because sometimes I missed an important one.
If you look at the android source code, it's easy to see that getFragmentManager()
will never return null :
public FragmentManager getFragmentManager() {
return mFragments;
}
Where mFragments is assigned only once through the whole class :
final FragmentManagerImpl mFragments = new FragmentManagerImpl();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With