我想要獲取活動中加載的碎片的後備堆棧計數。這裏的想法是,如果getBackStackEntryCount返回'0',運行我的onexitCheck()方法磨損/要求用戶退出或沒有,但我在第70行得到getBackStackEntryCount()的NPE。Android上的NPE BackStackEntry onBackPressed
我弄不清楚我有什麼問題。請看看我的方法,並在答案中添加更正。日Thnx。
public class RegulatoryDiscription extends Fragment {
. . .
}
. . .
//THE NPE STARTS HERE-->
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(getActivity().getFragmentManager().getBackStackEntryCount());
int bs = backEntry.getId();
public void onBackPressed() {
if (bs == 0) {
onexitCheck();
}
}
private Toast toast;
private long lastBackPressTime = 0;
public void onexitCheck() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(getActivity(), "Press back again to close this app", 4000);
toast.setDuration(4000);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.getActivity().onBackPressed();
}
}
NPE可能是backEntry.getId(),因爲backEntry爲空 – antlersoft