The approach you are using is not the best way to accomplish what you want to do. Android have a good support for listeners, and for communicating with fragments. So, lets see how to communicate fragment->activity direction.
First, you need to make your MainActivity a listener from what happens on a dialog, so the best way to do this is implementing DialogInterface.OnClickListener on your MainActivity and override the onClick(DialogInterface dialog, int which) method, this method will be called from your fragmen. So until now everything is done in your MainActivity.
Now, in your fragment, you have to override the onAttach(Activity activity) method, this is the first method called when the fragment is built and this method comes with our parent Activity, inside this method initialize the listener of your fragment (your MainActivity).
Your fragment should look like this:
private DialogInterface.OnClickListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
String title = args.getString("title");
String message = args.getString("message");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Calling our MainActivity Listener with a positive answer
listener.onClick(getDialog(), 1);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Calling our MainActivity Listener with a negative answer
listener.onClick(getDialog(), 0);
}
});
builder.create();
return builder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof DialogInterface.OnClickListener) {
listener = (DialogInterface.OnClickListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet DialogInterface.OnClickListener");
}
}
And your main activity onClick() method should look like this:
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//Do your negative thing
break;
case 1:
//Do your positive thing
break;
}
Toast.makeText(this, "You clicked "+ which, Toast.LENGTH_SHORT).show();
}
This is the best approach to do what you want to do, forget about "hard" cast your MainActivity class. Hope it helps you!