Android -replace运行片段

时间:2013-06-18 17:50:56

标签: java android android-activity android-fragments fragmenttransaction

我正在我的应用程序中实现导航抽屉,导航抽屉使用片段进行推荐,并在用户从导航抽屉中选择某些内容时更改正在运行的片段。当我尝试用新片段替换当前片段时,我的应用程序崩溃了。这是我用来替换片段的代码。

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)

1 个答案:

答案 0 :(得分:1)

我认为你在这一行有一个NPE android.support.v4.app.FragmentTransaction transaction = fragmentManager .beginTransaction();

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();替换为以下内容:

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

让我知道你的进展;)