DialogFragments に大きな問題があります。
私のDialogFragmentsは、正しく機能するためにサービス接続に依存しています。アクティビティが onServiceConnected() でボタンを描画し、サービスが DialogFragment で常に利用できるようにするため、ユーザーがボタンを押してダイアログをポップしても問題ありません。
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the service.
Intent gameServiceIntent = new Intent(this, GameService.class);
startService(gameServiceIntent);
bindService(gameServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
...
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// Assign the gameService object to a member variable.
GameActivity.this.gameService = ((GameService.LocalBinder)service).getService();
// Create a button that pops up a dialog.
// The dialog uses MainActivity.getGameService().
...
public GameService getGameService() {
return gameService;
}
...
そして、DialogFragment はゲーム サービスを使用します。
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.gameActivity = (GameActivity) getActivity();
gameActivity.getService();
ただし、向きが変わったとき (ユーザーがダイアログを開いた状態で電話を回転させたとき)、アプリケーションの状態を復元するとき、Android は onServiceConnected() を呼び出す前に DialogFragment.onCreateDialog() を呼び出します。次に、ダイアログが MainActivity.getGameService() を呼び出すと、null ポインター例外とクラッシュが発生します。
これは、onServiceConnected() に組み込まれている他のすべての UI コンポーネントの問題でもあります。たとえば、ListView と TableLayout です。onCreateDialog() は onServiceConnected() の前に呼び出されるため、Dialog の作成時には null です。
どうすればこれを修正できますか?!