1

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 です。

どうすればこれを修正できますか?!

4

1 に答える 1

1

同様の問題を次のように解決しました。

private Parcelable data;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Parcelable serviceData = myService.getSomeData();
    outState.putParcelable("data", serviceData)
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
       // create from bundle
       data = savedInstanceState.getParcelable("data");
    } else {
       // create from service
       data = myService.getSomeData();
    }
    ...
}
于 2013-10-28T18:01:15.630 に答える