DialogFragment 参数和空指针异常 [英] DialogFragment argument and nullpointer exception

查看:37
本文介绍了DialogFragment 参数和空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类应该将一个参数传递给 DialogFragment,但是我的应用程序在 onCreate 方法(对话框类的)中因 NullPointerException 而崩溃.对话框片段类部分代码:

My class should pass an argument to DialogFragment, but my app crashes inside onCreate method (of dialog class) for a NullPointerException. Dialog fragment class portion of code:

public class ConfirmDialog extends DialogFragment {

public ConfirmDialog() {}

 ConfirmDialog newInstance(String f) {
    ConfirmDialog d = new ConfirmDialog();

    Bundle args = new Bundle();
    args.putString("FILE_NAME", f);
    d.setArguments(args);

    return d;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    file = getArguments().getString("FILE_NAME");
}

我在这一行有空指针:

file = getArguments().getString("FILE_NAME");

我不知道为什么.我也粘贴了调用对话框的代码

And i don't know why. I paste also the code calls the dialog

private void showConfirmDialog(String file) {
    FragmentManager fm = getSupportFragmentManager();
    ConfirmDialog dialog = new ConfirmDialog();
    Log.i("SHOWFILEACTIVITY", file);
    dialog.newInstance(file);
    dialog.show(fm, "fragment_confirm_dialog");
}

这里的文件"字符串不为空,我已经检查过

Here the "file" string is not null, i've check it with

Log.i("SHOWFILEACTIVITY", file);

推荐答案

您正在通过构造函数创建一个 ConfirmDialog,然后调用 newInstance(),从而创建另一个(正确)ConfirmDialog.但是,您随后会丢弃该正确的实例.

You're creating a ConfirmDialog via the constructor, then calling newInstance(), which creates another (proper) ConfirmDialog. However you then discard that proper instance.

要解决这个问题:

你的 newInstance() 方法应该是静态的:

Your newInstance() method should be static:

public static ConfirmDialog newInstance(String f) {
    ConfirmDialog d = new ConfirmDialog();

    Bundle args = new Bundle();
    args.putString("FILE_NAME", f);
    d.setArguments(args);

    return d;
}

并且 showConfirmDialog() 应该改变,以便它正确使用 newInstance() 方法.

And showConfirmDialog() should be changed so it uses the newInstance() method properly.

private void showConfirmDialog(String file) {
    FragmentManager fm = getSupportFragmentManager();
    Log.i("SHOWFILEACTIVITY", file);

    ConfirmDialog dialog = ConfirmDialog.newInstance(file);
    dialog.show(fm, "fragment_confirm_dialog");
}

这篇关于DialogFragment 参数和空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆