【发布时间】:2015-04-24 17:21:51
【问题描述】:
我在进行 API 调用时很少遇到此错误。
java.lang.IllegalStateException: Fragment not attached to Activity
我尝试将代码放在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();
}
}
});
【问题讨论】:
-
cameraInfo.setId(getActivity().getResources().getString(R.string.camera_id));
标签: android android-fragments android-activity android-volley android-lifecycle