Skip to content

Instantly share code, notes, and snippets.

@apkelly
Last active June 20, 2016 07:34
Show Gist options
  • Save apkelly/2348af3fbb1e013d4d29 to your computer and use it in GitHub Desktop.
Save apkelly/2348af3fbb1e013d4d29 to your computer and use it in GitHub Desktop.
Handle IllegalStateException as a result of DialogFragment.show()
public abstract class AbstractActivity extends Activity {
private Map<String, Bundle> dialogs = new HashMap<String, Bundle>();
private boolean activityPaused = true;
@Override
public void onResume() {
super.onResume();
activityPaused = false;
// Show any dialogs that were attempted to be shown while paused (should only ever be 1 hopefully).
for (Map.Entry<String, Bundle> entry : dialogs.entrySet()) {
String fragmentName = entry.getKey();
Bundle fragmentState = entry.getValue();
// Instantiate dialog.
DialogFragment dialogFragment = (DialogFragment) Fragment.instantiate(this, fragmentName, fragmentState);
// Show dialog.
dialogFragment.show(getFragmentManager(), dialogFragment.getClass().getSimpleName());
getFragmentManager().executePendingTransactions();
// Remove fragment from map.
dialogs.remove(fragmentName);
}
}
@Override
public void onPause() {
activityPaused = true;
super.onPause();
}
protected void showDialogFragment(DialogFragment dialogFragment) {
if (activityPaused) {
// Delay showing of dialog until we're resumed.
Bundle savedState = new Bundle();
dialogFragment.onSaveInstanceState(savedState);
dialogs.put(dialogFragment.getClass().getName(), savedState);
} else {
// Show dialog straight away.
dialogFragment.show(getFragmentManager(), dialogFragment.getClass().getSimpleName());
getFragmentManager().executePendingTransactions();
}
}
}
public class MainActivity extends AbstractActivity implements MyFragment.IButtons {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
}
@Override
public void onMyButtonClicked() {
DialogFragment dialogFragment = MyDialogFragment.newInstance("Dummy Title", "Dummy Message");
showDialogFragment(dialogFragment);
}
}
public class MyDialogFragment extends DialogFragment {
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Make sure any arguments get saved.
outState.putAll(getArguments());
}
}
@erdemolkun
Copy link

Thanks for the inspiration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment