Android DialogFragment BadParcelableException

时间:2014-02-25 14:48:40

标签: android android-dialogfragment

我试着写一个小例子来重现我的问题:

public class ActivityA extends FragmentActivity{

  private void showMyDialog(){
    SelectionDialog dialog = SelectionDialog.newInstance("title", new SelectionDialog.UploadFolderSelectionDialogListener() {

                @Override
                public void writeToParcel(Parcel arg0, int arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public int describeContents() {
                    // TODO Auto-generated method stub
                    return 0;
                }

                @Override
                public void folderSelected() {
                    // TODO Auto-generated method stub

                }
            });
    dialog.show(getSupportFragmentManager());
  }
}

public class SelectionDialog extends DialogFragment {

  public static SelectionDialog newInstance(final String title, UploadFolderSelectionDialogListener listener) {
    SelectionDialog  dialog = new SelectionDialog ();
    Bundle args = new Bundle();
    args.putString("title", title);
    args.putParcelable("listener", listener);
    dialog.setArguments(args);
    return dialog;
  }

  @Override
  public Dialog onCreateDialog(final Bundle savedInstanceState) {
    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
    if (getArguments().containsKey("title")) {
        alertBuilder.setTitle(getArguments().getInt("title"));
    }
    return alertBuilder.create();
  }

  public interface UploadFolderSelectionDialogListener extends Parcelable {
    void folderSelected();
  }
}

问题:

  1. 确保选中“不要保持活动”开发人员选项
  2. 打开对话框
  3. 按HOME按钮
  4. 从HOME启动器中打开应用程序
  5. 调用getArguments()。get ...会导致异常:
  6. “android.os.BadParcelableException:Parcelable协议在类com上需要一个名为CREATOR的Parcelable.Creator对象.... $ 1”

    以下也没有解决问题:getArguments()。setClassLoader(getClass()。getClassLoader());

    从代码中删除args.putParcelable("listener", listener);可以避免崩溃。

0 个答案:

没有答案