我有一个预先加载的片段代码,必须像这样线性运行:
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
Context context = getActivity();
ArrayList<HashMap> itemList = new ArrayList<>();
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject c = response.getJSONObject(i);
HashMap<String, String> item = new HashMap<>();
Iterator<?> keys = c.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
item.put(key, c.getString(key));
}
itemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
TextView desc = (TextView) ncontent.findViewById(R.id.Desc);
TextView place = (TextView) ncontent.findViewById(R.id.Place);
TextView date = (TextView) ncontent.findViewById(R.id.Date);
NetworkImageView image = (NetworkImageView) ncontent.findViewById(R.id.Image);
HashMap i = itemList.get(0);
desc.setText(i.get("desc").toString());
place.setText(i.get("place").toString());
date.setText(i.get("date").toString());
ImageLoader imageLoader = DataController.getInstance(getActivity()).getImageLoader();
image.setImageUrl("http://192.168.0.101/" + i.get("image").toString(), imageLoader);
LruBitmapCache lruBitmapCache = new LruBitmapCache();
lruBitmapCache.getBitmap("http://192.168.0.101/" + i.get("image").toString());
}
}, null);
DataController.getInstance(getActivity()).addToRequestQueue(req);
问题在于,当我插入一些Listener时,会在片段关闭时创建后台进程,继续运行。
imageLoader.get("http://192.168.0.101/" + i.get("image").toString(), new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
Image = (ImageView) ncontent.findViewById(R.id.Image);
Image.setImageBitmap(response.getBitmap());
}
} });
在算法运行之前关闭片段会返回以下错误:
java.lang.IllegalStateException: Fragment Details3{3e80163e} not attached to Activity
我想杀死关闭片段时正在运行的任何过程。
答案 0 :(得分:1)
在片段onDestroy生命方法中清除由DataController控制的请求。
在onResponse方法中,首先需要检查上下文是否为空。