我正在尝试从json获取图像的url,然后使用该url下载图像。但是问题是url被提取到如此晚/慢,imagerequest报告urlFull为null。甚至在使用DataCallback接口之后。任何解决方案,以便两个请求同步发生?
编辑 - 我注意到一个奇怪的事情是当我第二次点击按钮时这段代码完美无缺。但在第一次它说Bad url null
我在一个调用 -
的按钮上设置了onclicklistenerpublic void fetchSave(String photoJson) {
fetchData(new DataCallback() {
@Override
public void onBitmapSuccess(Bitmap result) {
Utils utils = new Utils(getActivity());
utils.saveImageSDCard(result);
}
@Override
public void onJsonSuccess(JSONObject result) {
try {
JSONArray mediaContentArray = result.getJSONObject(TAG_ENTRY).getJSONObject(TAG_MEDIA_GROUP).getJSONArray(TAG_MEDIA_CONTENT);
JSONObject mediaObject = (JSONObject) mediaContentArray.get(0);
urlFull = mediaObject.getString(TAG_IMG_URL);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "Full image url " + urlFull);
}
}, photoJson);
}
fetchData()如下 -
public void fetchData(final DataCallback callback, String photoJson) {
RequestFuture<JSONObject> future = newFuture();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, photoJson, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "JsonObject response= "+response.toString());
callback.onJsonSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), getString(R.string.toast_unknown_error), Toast.LENGTH_LONG).show();
}
});
jsonObjectRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
AppController.getInstance().getRequestQueue().getCache().remove(photoJson);
final ImageRequest imageRequest = new ImageRequest(urlFull, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
Log.d(TAG, "Bitmap response");
callback.onBitmapSuccess(response);
}
}, 0, 0, ImageView.ScaleType.CENTER_CROP, null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Couldn't Download", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(imageRequest);
}
答案 0 :(得分:1)
您可以在第一个请求的onResponse()方法中发送第二个请求,这样您就可以确保数据不为空
答案 1 :(得分:0)
Volley通过RequestFutures支持阻止请求。您创建了一个普通请求,但将其回调设置为您的未来请求,这只是volley对标准Java期货的扩展。对future.get()的调用将阻止。
它看起来像这样
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future)
volleyRequestQueue.add(request);
try {
JSONObject response = future.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}