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() 时,我得到一个空指针异常和崩溃。

这也是所有其他内置于 onServiceConnected() 的 UI 组件的问题。例如,一个 ListView 和一个 TableLayout。它们在创建 Dialog 时为空,因为在 onServiceConnected() 之前调用了 onCreateDialog()。

我怎样才能解决这个问题?!

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 回答