如何使用Retrofit 2

时间:2016-05-20 15:03:35

标签: android dialog retrofit retrofit2 dismiss

我正在使用Retrofit 2在Fragment中向我的服务器发出POST请求,如下所示:

Call<MyResponse> call = apiService.myPost(params);
call.enqueue(myCallback);

mProgress = ProgressDialog.show(getActivity(), "Working", "Working"", true);

我想在请求完成时关闭ProgressDialog,如下所示:

class myCallback {
    onResponse() {
       mProgress.dismiss();
    }
    onFailture() {
       mProgress.dismiss();
    }
}

但是这种方法效果不好,因为用户可以旋转或离开当前的Activity,导致出现此错误:

Fatal Exception: java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{1ec6c6d0 V.E..... R.....ID 0,0-513,242} not attached to window manager
       at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:396)
       at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:322)
       at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
       at android.app.Dialog.dismissDialog(Dialog.java:341)
       at android.app.Dialog.dismiss(Dialog.java:324)

如何在这种情况下正确解除对话?

2 个答案:

答案 0 :(得分:2)

当Fragment与其Activity分离时,您应该关闭对话框,或者添加一个检查以查看Fragment是否仍然附着。以下示例调用isAdded()进行检查。

onResponse() {
     if (isAdded()) {
         mProgress.dismiss();
     }
}

答案 1 :(得分:0)

Call<MyResponse> call = apiService.myPost(params);
call.enqueue(new Callback<MyResponse>() {
    @Override
    public void onResponse(Response<Repo> response) {
        mProgress.dismiss();
    }

    @Override
    public void onFailure(Throwable t) {
        mProgress.dismiss();
    }
});