android - NullPointerException 调用 Dialog Fragment 时

标签 android dialog fragment

我想使用此 [链接][1] 之后的 fragment 创建对话框

这是我的对话 fragment 代码

public class AlertFragmentDialog extends DialogFragment 
{   
    public static final int DIALOG_EXIT_ALERT = 1;

    private static final String KEY_TITLE = "titles";
    private static final String KEY_DIALOG = "dialogtype";

    public static DialogFragment newInstance(int _title,int _dialogType){
        AlertFragmentDialog frag = new AlertFragmentDialog();
        Bundle args = new Bundle();
        args.putInt(KEY_TITLE, _title);
        args.putInt(KEY_DIALOG, _dialogType);
        frag.setArguments(args);        
        return null;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {   
        switch(getArguments().getInt(KEY_DIALOG))
        {
            case DIALOG_EXIT_ALERT : 
                return new AlertDialog.Builder(getActivity()).setTitle(getArguments().getInt(KEY_TITLE))
                        .setPositiveButton(R.string.global_yes,new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int whichButton) 
                            {
                                ((MainActivity)getActivity()).doYesConfirmationClick();
                            }
                        })
                        .setNegativeButton(R.string.global_no, new DialogInterface.OnClickListener() 
                        {
                            public void onClick(DialogInterface dialog, int whichButton) 
                            {
                                ((MainActivity)getActivity()).doNoConfirmationClick();
                            }
                        }).create();
        }
        return null;
    }
}

并使用这段代码调用它

FragmentManager fm = getSupportFragmentManager();
        DialogFragment alertDialog = AlertFragmentDialog.newInstance(R.string.global_exit_alert,AlertFragmentDialog.DIALOG_EXIT_ALERT);
        alertDialog.show(fm, "dialog");

但是当我运行时,我的模拟器出现 NullPointerException 错误。 alertDialog.show(fm, "dialog") 出错; 请帮助我不确定我的代码有什么问题..

最佳答案

您的 newInstance() 返回 null。将其更改为返回 frag

关于android - NullPointerException 调用 Dialog Fragment 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813510/

相关文章:

android - adb:在 Git Bash 中找不到命令

android - 如何让 Espresso 等待由 firebase 调用触发的 Activity ?

Python:tkinter askyesno 方法打开一个空窗口

android - 启动对话 Activity 和重新创建 Activity 时未调用 OnActivityResult

android - 如何清除 fragment 中的参数?

android - 寻找Android的 View 效果

java - 安卓.view.WindowManager$BadTokenException : Unable to add window -- token null is not for an application

android - 计时器线程刷新android上的 fragment

android - 为什么 Fragments 需要交易?

Android Studio - 单个项目中具有共同依赖项的多个 android 应用程序