【问题标题】:NullPointerException When calling Dialog FragmentNullPointerException 调用 Dialog Fragment 时
【发布时间】:2013-05-29 12:09:09
【问题描述】:

我想使用以下 [链接][1] 的片段创建对话框,

这是我的对话框片段代码

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"); 请帮助我不确定我的代码有什么问题..

【问题讨论】:

  • 你的 logcat 里有什么? NullpointerExceptions 向您显示发生错误的行。检查这一行

标签: android dialog fragment


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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 frag;  // you were returning null
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多