0

此代码在某些设备上崩溃,但在其他设备上正常工作。片段中的OnPrepareOptionsMenu在设备上具有不同的行为

@Override 
public void onPrepareOptionsMenu(Menu menu) { 
    super.onPrepareOptionsMenu(menu); 
    boolean isSelectModeActive = mRecyclerAdapter.getSelectedItemCount() > 0; 
    mCallback.onChangeMenuInSelectionMode(menu, isSelectModeActive); 
} 

附上回调onAttach方法:

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    Activity activity = (Activity) context; 
    try { 
     mCallback = (iSongsListFragmentEventListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
              + " must implement iSongsListFragmentEventListener"); 
    } 
} 

堆栈跟踪说mCallback是空的onPrepareOptions方法,但是为什么呢? 我在我的nexus 4和所有模拟器上测试了这段代码 - 没有崩溃,但有些用户崩溃了。

Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'void chuprin.serg.com.autotagger.fragments.SongsListFragment$iSongsListFragmentEventListener.onChangeMenuInSelectionMode(android.view.Menu, boolean)' on a null object reference 
    at chuprin.serg.com.autotagger.fragments.SongsListFragment.onPrepareOptionsMenu(SongsListFragment.java:292) 
+0

对您的对象'mCallback'进行空检查。 – Exception

回答

0

你在哪里调用片段中的setHasOptionsMenu(true)?它在构造函数中吗?从onCreate()调用它。

+0

我在onCreate()中调用setHasOptionsMenu(true) – Creati8e

相关问题