5

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

I have the nullpointer at this line:

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);
giozh
  • 9,868
  • 30
  • 102
  • 183

1 Answers1

7

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");
}
A--C
  • 36,351
  • 10
  • 106
  • 92
  • ok thanks, it works. I've never used newInstance function and i've made a mistake! but why newInstance should be static? – giozh Mar 17 '13 at 17:47
  • 1
    @giozh since we want to create a `new` instance of the Dialog, it's a bad design approach to rely on an *already created* instance of the Dialog. Keeping the method static removes dependencies and results in less object creation. – A--C Mar 17 '13 at 17:51