2017-06-01 41 views
-2

我在onBackPressed()方法中有致命的异常:对空对象引用。 如何正确处理异常? 我的代码:.onBackPressed()中的空对象引用

@Override 
public void onBackPressed() { 
    List fragments = getSupportFragmentManager().getFragments(); 
    BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1); 

    if (fragments != null && !currentFragment.onActivityBackPress()) { 
     super.onBackPressed(); 
    } 
} 
+1

的可能的复制[什么是空指针异常,以及如何解决?(https://stackoverflow.com/问题/ 218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – VishnuSP

+0

*如何正确处理异常?*修复它:1.检查什么是空2.不要使用null参考 – Selvin

+0

@VishnuSP你是否看到我正在处理不存在的数据?但没有拦截。你有没有读过你发布的答案和我的问题? – Roman

回答

1

它会容易得多,如果你也给堆栈跟踪。 但是有可能你正在检查空说错话,改变fragmentscurrentFragment

@Override 
public void onBackPressed() { 
    List fragments = getSupportFragmentManager().getFragments(); 
    BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1); 

    if (currentFragment != null && !currentFragment.onActivityBackPress()) { 
     super.onBackPressed(); 
    } 
} 
+0

感谢您的回答。我真的不明白为什么如果有一个片段,目前的片段不存在。在模拟器上,没有错误,只有在设备上有时会出现这个错误。我从Fabric – Roman

+0

中得到它,也许片段列表为空 –

相关问题