我如何等待 Volley 的响应?

How do I wait for response of Volley?

为了总结我的问题,我有一个用 Android Volley Library 写的请求。

我需要填写 chartDataList。但是每当我在 3 秒后异步填充自身时调用它 return 空数组的方法时就会出现问题。我想等待回复,但我不知道该怎么做?

这是我的代码:

 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;
}

Response 函数是一个回调函数,将在您的请求得到 processed/server 响应后执行。我建议执行您的逻辑,该逻辑取决于您的 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.
}