Method invocation highlighed error in Android Studio

谁都会走 提交于 2019-12-22 03:53:15

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17270838/method-invocation-highlighed-error-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!