在进行 API 调用时,我很少收到此错误。
java.lang.IllegalStateException: Fragment not attached to Activity
我尝试将代码放入isAdded()方法中以检查片段当前是否已添加到其活动中,但我仍然很少收到此错误。我不明白为什么我仍然收到此错误。我该如何预防?
isAdded()
它在行上显示错误-
cameraInfo.setId(getResources().getString(R.string.camera_id));
下面是我正在进行的示例 api 调用。
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(); } } }