从Activity调用DialogFragment会导致“IllegalStateException:fragment not attached to Activity”错误。

3
我有一个Activity,里面包含一个Fragment。我需要显示一个DialogFragment(在Fragment内声明为public和static),让用户退出登录。在这个对话框中,我需要发出服务器请求,并在完成后关闭对话框。
问题在于,当服务器请求到达时,我会收到错误消息“IllegalStateException: fragment not attached to Activity”。
有没有办法解决这个问题?
编辑:
以下是logcat输出:
E/AndroidRuntime(13849): java.lang.IllegalStateException: Fragment LogoutDialogFragment{4256be70} not attached to Activity
E/AndroidRuntime(13849):    at android.support.v4.app.Fragment.startActivity(Fragment.java:836)
E/AndroidRuntime(13849):    at nl.emte.merchant.ui.EmteActivity$LogoutDialogFragment$1$1.onDataLoad(EmteActivity.java:328)
E/AndroidRuntime(13849):    at nl.emte.merchant.api.EmteApiManager$5.onPostExecute(EmteApiManager.java:212)

以下是LogOutFragment的代码,它是一个DialogFragment,允许用户退出登录:

public static class LogoutDialogFragment extends SherlockDialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setCancelable(true);
            builder.setMessage(R.string.logout_screen_description);
            builder.setPositiveButton(R.string.logout_positive_button_lbl,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                            EmteApiManager.getInstance().doLogout(new DataLoadListner() {

                                @Override
                                public void onError(Object errorMessage) {
                                }

                                @Override
                                public void onDataLoad(Object result) {
                                    Intent intent = new Intent(
                                            IntentActions.ACTION_LOGIN);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                }
                            });

                        }
                    }).setNegativeButton(R.string.logout_negative_button_lbl,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            return builder.create();
        }
    }

提前感谢您!


需要更多信息才能帮助您,如果您可以发布一些代码和您的logcat,那将是非常好的。 - zozelfelfo
@zozelfelfo,这是给你的 ;) - noloman
请问您能否将 EmteActivity.java:328 突出显示一下? - zozelfelfo
2个回答

5

您可以使用一个静态类来使用应用程序上下文进行回调。

活动和片段是短暂的,因此依赖它们在异步回调后处于良好状态是危险的。


2

我认为在调用 startActivity() 之后再调用 dismiss()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接