【问题标题】:When restoring from an orientation change, DialogFragment onCreateDialog() is called before onServiceConnected()从方向更改恢复时,在 onServiceConnected() 之前调用 DialogFragment onCreateDialog()
【发布时间】:2013-10-18 23:27:27
【问题描述】:

我的 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 时它们为 null,因为在 onServiceConnected() 之前调用了 onCreateDialog()。

我该如何解决这个问题?!

【问题讨论】:

    标签: android android-fragments android-service android-dialog android-dialogfragment


    【解决方案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();
        }
        ...
    }
    

    【讨论】:

    • 有趣 :) 感谢您的回答。
    猜你喜欢
    • 2012-10-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多