小编典典

java.lang.IllegalStateException:片段未附加到活动

all

在进行 API 调用时,我很少收到此错误。

java.lang.IllegalStateException: Fragment  not attached to Activity

我尝试将代码放入isAdded()方法中以检查片段当前是否已添加到其活动中,但我仍然很少收到此错误。我不明白为什么我仍然收到此错误。我该如何预防?

它在行上显示错误-

I tried putting the code inside isAdded() method to check whether fragment
is currently added to its activity but still i rarely gets this error. I fail
to understand why I am still getting this error. How can i prevent it?

Its showing error on the line-

cameraInfo.setId(getResources().getString(R.string.camera_id));

Below is the sample api call that i am making.

SAPI.getInfo(getActivity(),
                new APIResponseListener() {
                    @Override
                    public void onResponse(Object response) {


                        cameraInfo = new SInfo();
                        if(isAdded()) {
                            cameraInfo.setId(getResources().getString(R.string.camera_id));
                            cameraInfo.setName(getResources().getString(R.string.camera_name));
                            cameraInfo.setColor(getResources().getString(R.string.camera_color));
                            cameraInfo.setEnabled(true);
                        }


                    }

                    @Override
                    public void onError(VolleyError error) {
                        mProgressDialog.setVisibility(View.GONE);
                        if (error instanceof NoConnectionError) {
                            String errormsg = getResources().getString(R.string.no_internet_error_msg);
                            Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
                        }
                    }
                });

阅读 56

收藏
2022-08-27

共1个答案

小编典典

发生此错误是由于两个因素的综合影响:

  • HTTP 请求在完成时调用onResponse()onError()(在主线程上工作)而不知道它是否Activity仍在前台。如果不Activity存在(用户导航到其他地方),则getActivity()返回 null。
  • VolleyResponse被表示为一个匿名的内部类,它隐含地持有对外部Activity类的强引用。这会导致典型的内存泄漏。

要解决此问题,您应该始终执行以下操作:

Activity activity = getActivity();
if(activity != null){

    // etc ...

}

并且,也可以isAdded()在该onError()方法中使用:

@Override
public void onError(VolleyError error) {

    Activity activity = getActivity(); 
    if(activity != null && isAdded())
        mProgressDialog.setVisibility(View.GONE);
        if (error instanceof NoConnectionError) {
           String errormsg = getResources().getString(R.string.no_internet_error_msg);
           Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
        }
    }
}
2022-08-27