I have this android.app.DialogFragment
:
public class MyDialog extends DialogFragment {
private Callback callback;
public static MyDialog newInstance() {
return new MyDialog();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog dialog = new AlertDialog.Builder(getActivity())
//set more things
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
callback.run(); //callback is null
}).create();
return dialog;
}
public void setCallback(Callback callback) { this.callback = callback; }
}
and from my activity:
MyDialog dialog = MyDialog.newInstance();
dialog.setCallback(myCallback);
dialog.show(getFragmentManager(), "dialog");
But when I click "Ok" button, it crashes beacuse callback is null
. myCallback is never null
I found something. onCreateDialog
is called twice and the second time callback
is null
:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Log.d("test", "onCreateDialog (" + this + ") -> " + callback);
//more code
}
It prints:
onCreateDialog (MyDialog{18ea188e}) -> com.house.hehe.MyActivity$3@3afbe8af
onCreateDialog (MyDialog{22199eaa}) -> null
How is it possible? Why are there two different instances? Why is onCreateDialog
called twice?
I don't know what is happening but I have solved by doing callback
an static static:
private static Callback callback;
public static MyDialog newInstance(Callback callback) {
MyDialog.callback = callback;
return new MyDialog();
}
It is an ugly solution... oh well...