显示片段会抛出Null指针异常

时间:2015-04-17 11:08:48

标签: android android-fragments android-support-library

我有一个针对api 9级和用户app compat库的Android应用程序。所以我有这个问题,当我点击一个按钮它应该显示一个片段,但我不知道为什么这是不可能的,因为它在log cat中显示我这个错误:

/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myapp, PID: 14290
java.lang.NullPointerException
        at com.myapp.Main.onClick(Main.java:1204)
        at android.view.View.performClick(View.java:4654)
        at android.view.View$PerformClick.run(View.java:19438)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5602)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)

这是我得到的错误:

 @Override
    public void onClick(View v) {
        Log.d("--", "view clicked");
        if (adapter != null)
            if (!menuShown && adapter.getNextPrayTime() != null) {
                switch (v.getId()) {
                    case R.id.action_share:
                        View view = findViewById(R.id.main_rl);
                        shareImage(view, false);
                        break;
                    case R.id.action_menu:
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.NEXT_TIME,
                                adapter.getNextPrayTime());
                        MenuFragment menuFragment = new MenuFragment();
                        menuFragment.setArguments(bundle);
                        Log.e("--",menuFragment+" ex. "+bundle);
    //this is line 1204
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.commitAllowingStateLoss();
                        transaction.setCustomAnimations(
                                R.anim.slide_in_from_bottom,
                                R.anim.slide_out_to_bottom,
                                R.anim.slide_in_from_bottom,
                                R.anim.slide_out_to_bottom);
                        transaction.add(android.R.id.content, menuFragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                        menuShown = true;
                        break;
                }
            }
    }

有没有人知道为什么会这样,所以我可以解决这个问题?

由于

修改:此活动扩展了ActionBarActivity

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

transaction.commitAllowingStateLoss();