DialogFragment.show()抛出NullPointerException

时间:2015-04-15 21:43:30

标签: java android android-fragments nullpointerexception

我制作了我的第一个主要Android应用,并且我试图在ActionBarActivity中显示对话框。我已经创建了DialogFragment的子类:

public class QuestionFragment extends DialogFragment {
private final String[] CHOICES = {"More than once per day","Once per day","Less often"};

public QuestionFragment() {
    //Required empty constructor
}

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("How often do you take this medication?")
            .setItems(CHOICES, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //options for int which go here
                }
            });
    return builder.create();
}
}

我尝试以与Android开发人员教程解释它的方式非常相似的方式使用show方法。单击按钮时,该对话框应该出现:

public void toAdd(View view) {
    QuestionFragment dialog = new QuestionFragment();
    dialog.show(dialog.getFragmentManager(),"question");
}

当我尝试这个时,我得到:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
        at android.app.DialogFragment.show(DialogFragment.java:228)
        at gianttine.rescription.TodayMeds.toAdd(TodayMeds.java:49)
        ...

我还尝试将(dialog.getFragmentManager(),"question");更改为(getFragmentManager(),"question");,我还尝试制作FragmentManager对象,然后再将其传递给show()。< / p>

由于我是Android开发的新手,我可能在该代码中有一些糟糕的设计选择,但我希望找出为什么会有异常以及我需要做些什么来使对话框正确显示。

1 个答案:

答案 0 :(得分:2)

当您的对话框未附加到活动时,您无法使用dialog.getFragmentManager(),因此CAN可以访问FragmentManager。只有在它附加后才能实现。

您需要做的是获取一个有效的FragmentManager,即从组件调用toAdd()方法。

所以:

public void toAdd(View view) {
    QuestionFragment dialog = new QuestionFragment();
    dialog.show(getFragmentManager() /*<--- depends where it's invoked, inside an Activity it's the right way, inside another Fragment, it would be getChildFragmentManager*/,"question");
}