我有一个包含 fragment 的 Activity,我需要显示一个 DialogFragment(在 fragment 内声明为公共(public)和静态)用于注销用户。 在此对话框中,我需要发出服务器请求,完成后,必须关闭该对话框。
这里的问题是,当服务器请求到达时,我收到错误“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();
}
}
提前致谢!
最佳答案
您可以使用一个静态类,该类使用回调的应用程序上下文。
Activity 和 Fragment 是短暂的,因此依赖它们在异步回调后保持良好状态是危险的。
关于android - 从 Activity 调用 DialogFragment 导致 "IllegalStateException: fragment not attached to Activity",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23931609/