[英]How do I wait for response of Volley?
To summarize my problem i have a request written with Android Volley Library.总结我的问题,我有一个用 Android Volley Library 编写的请求。
I need fill chartDataList
.我需要填写chartDataList
。 But there is a problem whenever i call the method it return a null array after 3 seconds it filling itself asynchronously.但是,每当我调用该方法时,它就会在 3 秒后返回一个 null 数组,它会异步填充自己。 I want to wait for response but i dont have any idea how can i do that?我想等待回复,但我不知道我该怎么做?
Here is my codes:这是我的代码:
public List<ChartData> getVolleyResponse() {
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest req = new JsonObjectRequest(
Request.Method.GET,
urlCreator(getCoinName()),
null,
response -> {
try {
JSONArray arr = response.getJSONArray("prices");
ChartData chartData = new ChartData();
for (int i = 0; i < arr.length(); i++) {
JSONArray jsonArray = arr.getJSONArray(i);
chartData.setTimeStamp(timeStampConverter(jsonArray.getString(0)));
chartData.setCost(jsonArray.getDouble(1));
chartDataList.add(chartData);
}
} catch (JSONException e) {
e.printStackTrace();
}
},
error -> {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
});
requestQueue.add(req);
return chartDataList;
}
The Response function is a callback that will be executed after your request has processed/server has responded.响应 function 是一个回调,将在您的请求已处理/服务器响应后执行。 I would recommend executing your logic that depends on the response data within your Response function callback.我建议执行您的逻辑,该逻辑取决于您的响应 function 回调中的响应数据。 This is non-blocking but works with the asynchronous design of Volley:这是非阻塞的,但适用于 Volley 的异步设计:
public List<ChartData> getVolleyResponse() {
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest req = new JsonObjectRequest(
Request.Method.GET,
urlCreator(getCoinName()),
null,
response -> {
try {
JSONArray arr = response.getJSONArray("prices");
ChartData chartData = new ChartData();
for (int i = 0; i < arr.length(); i++) {
JSONArray jsonArray = arr.getJSONArray(i);
chartData.setTimeStamp(timeStampConverter(jsonArray.getString(0)));
chartData.setCost(jsonArray.getDouble(1));
chartDataList.add(chartData);
}
// The request has processed/server has responded.
// Do something with your response here.
// ...
} catch (JSONException e) {
e.printStackTrace();
}
},
error -> {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
});
requestQueue.add(req);
// We're handling the response asynchronously, so there shouldn't be anything to return here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.