總結一下我的問題,我有一個用 Android Volley 庫撰寫的請求。
我需要填寫chartDataList。但是每當我呼叫該方法時都會出現問題,它會在 3 秒后回傳一個空陣列,它會異步填充自己。我想等待回復,但我不知道我該怎么做?
這是我的代碼:
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;
}
uj5u.com熱心網友回復:
Response 函式是一個回呼,將在您的請求已處理/服務器已回應后執行。我建議執行依賴于回應函式回呼中的回應資料的邏輯。這是非阻塞的,但適用于 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.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369640.html
標籤:爪哇 安卓 异步 数组列表 android-volley
