我在 java 类中使用 JsonObjectRequest 和 Volley 发出请求,一旦获得数据,我无法将其发送到需要使用它的活动。我尝试使用回调,但我不知道我做错了什么。我已经尝试了几件事,但都没有奏效。我在我的请求类中正确获取了数据,所以问题是从活动中获取该数据。
我认为我的问题与回调有关,但正如我所说,我已经尽我所能。
任何帮助,将不胜感激!
这是我的请求代码:
public ArrayList<Coin> getMarketSummary(final DashboardActivity.CoinCallback callback, ArrayList<Coin> listAux, Context context) { Log.d("chegamos a entrar en getCOinData??", "Entramos en getMarketSummary"); listCoins.clear(); requestQueue = Volley.newRequestQueue(context); for (Coin coinAux : listAux) { this.coin = coinAux; if (!coin.getShortName().equals("BTC")) { //we create the URL for request the market String urlMarket = "https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-SHORTNAME"; String coinShortName = coin.getShortName(); urlMarket = urlMarket.replaceAll("SHORTNAME", coinShortName.toLowerCase()); //once created the url, we create the request with JSONObject JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlMarket, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray result = response.getJSONArray("result"); //we loop the response for (int i = 0; i < result.length(); i++) { coin.setHigh(Double.parseDouble(result.getJSONObject(i).getString("High"))); coin.setLow(Double.parseDouble(result.getJSONObject(i).getString("Low"))); coin.setLast(Double.parseDouble(result.getJSONObject(i).getString("Last"))); coin.setVolInBtc(Double.parseDouble(result.getJSONObject(i).getString("BaseVolume"))); coin.setBid(Double.parseDouble(result.getJSONObject(i).getString("Bid"))); coin.setAsk(Double.parseDouble(result.getJSONObject(i).getString("Ask"))); coin.setPrevDay(result.getJSONObject(i).getString("PrevDay")); listCoins.add(coin); callback.onSuccess(listCoins); } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); requestQueue.add(request); } } return listCoins; }
这就是我初始化回调的方式(在发出请求之前):
public void initCallback() { this.coinCallback = new CoinCallback() { @Override public void onSuccess(ArrayList<Coin> coinListFromRequest) { coinList=coinListFromRequest; } }; }
这是我调用请求的方式(在我初始化回调之后):
coinList = bittrexAPIRequest.getMarketSummary(coinCallback, coinList, this); adapter.notifyDataSetChanged();
最后,我的 CoinCallback 接口:
public interface CoinCallback { void onSuccess(ArrayList<Coin> coinList); }