0

我在我的應用程序中實現了一個導航抽屜,導航抽屜建議使用片段,並在用戶從導航抽屜中選擇某些內容時更改正在運行的片段。當我嘗試用新的片段替換當前片段時,我的應用程序崩潰。這裏是我用來代替片段的代碼。Android -replace運行片段

Body newFragment = new Body(); 

      android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager(); 
      android.support.v4.app.FragmentTransaction transaction = fragmentManager 
        .beginTransaction(); 

      // Replace whatever is in the fragment_container view with this 
      // fragment, 
      // and add the transaction to the back stack 
      transaction.replace(R.id.llhome, newFragment); 
      transaction.addToBackStack(null); 

      // Commit the transaction 
      transaction.commit(); 

編輯:下面是我的logcat

06-18 13:53:10.142: E/AndroidRuntime(17700): FATAL EXCEPTION: main 
06-18 13:53:10.142: E/AndroidRuntime(17700): java.lang.NullPointerException 
06-18 13:53:10.142: E/AndroidRuntime(17700): at com.OptimusApps.stayhealthy.Body.<init>(Body.java:31) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at com.OptimusApps.stayhealthy.MainActivity$DrawerItemClickListener.onItemClick(MainActivity.java:129) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.widget.AbsListView.performItemClick(AbsListView.java:1060) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2516) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.widget.AbsListView$1.run(AbsListView.java:3170) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.os.Handler.handleCallback(Handler.java:605) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.os.Handler.dispatchMessage(Handler.java:92) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.os.Looper.loop(Looper.java:137) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at android.app.ActivityThread.main(ActivityThread.java:4575) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at java.lang.reflect.Method.invokeNative(Native Method) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at java.lang.reflect.Method.invoke(Method.java:511) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 
06-18 13:53:10.142: E/AndroidRuntime(17700): at dalvik.system.NativeStart.main(Native Method) 
+0

你可以請你在Logcat中看到的崩潰日誌? – petey

+0

@forgivegod我編輯我的問題 – user222786

+0

你可以發佈Body.java第31行(可能是構造函數嗎?) – JRomero

回答

1

我認爲你有一個NPE在該行android.support.v4.app.FragmentTransaction transaction = fragmentManager .beginTransaction();

替換您android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();由下列之一:

android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();

讓我知道喲你的進步;)