Skip to content

Instantly share code, notes, and snippets.

@twelve17
Last active August 29, 2015 14:06
Show Gist options
  • Save twelve17/c3733e285425f7861c96 to your computer and use it in GitHub Desktop.
Save twelve17/c3733e285425f7861c96 to your computer and use it in GitHub Desktop.
Workaround for Android Issue 14616: ActivityUnitTestCase crashes when dialogs are spawned.
public class MyActivity extends Activity {
public void methodTriggeredFromASomeAction(View view) {
final ProgressDialogFragment pDialogFragment = ProgressDialogFragment.newInstance("Dialog Text..");
pDialogFragment.show(getFragmentManager(), "dialog");
//...
pDialogFragment.dismiss();
}
}
/**
* For whatever reason, wrapping a ProgressDialog in a Fragment prevents the "BadTokenException"
* exception from happening in ActivityUnitTestCase classes.
*/
public class ProgressDialogFragment extends DialogFragment {
public static ProgressDialogFragment newInstance(String text) {
ProgressDialogFragment frag = new ProgressDialogFragment();
Bundle args = new Bundle();
args.putString("text", text);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ProgressDialog dialog = new ProgressDialog(getActivity());
String text = getArguments().getString("text");
dialog.setMessage(text);
return dialog;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment