To summarize my problem i have a request written with Android Volley Library.
I need fill chartDataList
. But there is a problem whenever i call the method it return a null array after 3 seconds it filling itself asynchronously. 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;
}
CodePudding user response:
The Response function is a callback that will be executed after your request has processed/server has responded. I would recommend executing your logic that depends on the response data within your Response function callback. This is non-blocking but works with the asynchronous design of 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.
}