我的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()时,我得到一个空指针异常并崩溃。
对于在ServiceConnected()中构建的所有其他UI组件,这也是一个问题。例如,ListView和TableLayout。 创建Dialog时它们为null,因为在onServiceConnected()之前调用onCreateDialog()。
我该如何解决这个问题?!
答案 0 :(得分: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();
}
...
}