DialogFragment argument and nullpointer exception

后端 未结 1 431
陌清茗
陌清茗 2021-01-05 18:24

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

1条回答
  •  臣服心动
    2021-01-05 19:25

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

    To fix this:

    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;
    }
    

    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");
    }
    

    0 讨论(0)
提交回复
热议问题