问题描述
我对 Android Studio 有点困惑.之前在Eclipse中没见过这种错误.
Im a little bit confused in Android Studio. I didint seen this kind of errors in Eclipse before.
示例:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction tf = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(AddDialogFragment.TAG);
这段代码工作正常,但是 fragmentManager.beginTransaction();被突出显示并说:方法调用 'fragmentManager.beginTransaction' 可能会产生更少的 'java.lang.NullPointerException'... (Ctrl+F1)
this code is working fine, but fragmentManager.beginTransaction(); gets highlighted and says:Method invocation 'fragmentManager.beginTransaction' may produce 'java.lang.NullPointerException' less... (Ctrl+F1)
此检查报告指定检查范围内始终为真或为假的那些条件,并根据代码的数据流分析指出可能抛出 RuntimeException 的位置.此检查还报告 Nullable/NotNull 合同违规.可以配置支持合约的注释(默认情况下将使用 annotations.jar 中的 @Nullable/@NotNull 注释)
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)
我之前需要检查 Null 吗?
Do i have to check for Null before?
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager != null)
FragmentTransaction tf = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(AddDialogFragment.TAG);
我以前从未在任何 Tut 或 Example 中看到过这种情况.如果这是一个愚蠢的问题,那么抱歉,但我仍然是初学者:).
I have never seen this in any Tut or Example before.If this is a stupid question than sorry, but im still a beginner :).
推荐答案
就我所见,Android Studio 对潜在的 NullPointerExceptions
显示了过多的警告,即使对于永远不会返回的方法空值.我只是忽略了其中的一些,但仔细检查所有这些很有用,因为有时我会错过一个重要的.
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.
如果你查看 android 源代码,很容易看出 getFragmentManager()
永远不会返回 null :
If you look at the android source code, it's easy to see that getFragmentManager()
will never return null :
public FragmentManager getFragmentManager() {
return mFragments;
}
mFragments 在整个班级中只分配一次:
Where mFragments is assigned only once through the whole class :
final FragmentManagerImpl mFragments = new FragmentManagerImpl();
这篇关于方法调用在 Android Studio 中突出显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!