在进行 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?
isAdded()
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(); } } });
发生此错误是由于两个因素的综合影响:
onResponse()
onError()
Activity
getActivity()
Response
要解决此问题,您应该始终执行以下操作:
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(); } } }