如何获得onResponse的返回值

时间:2019-05-15 13:01:46

标签: java android

我知道这就是答案,但是我无法将其添加到我的代码中。

How can I return value from function onResponse of Volley? <------

像这里创建界面一样。 我都做了 我只是不知道如何将我的代码转换为它,以及如何在其他活动中使用返回值。

    public void priceDate(Context contex, final String coin) {

    String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;


    //String a =
   //json_Parser = new JSONParser(_usd);

    RequestQueue requestQueue = Volley.newRequestQueue(contex);



    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {


        @Override
        public void onResponse(JSONObject response) {

            //Log.d("Main",response.toString());}
            DecimalFormat formatter = new DecimalFormat("#,###,###");
                String yourFormattedString = formatter.format(100000);
                try {
                    JSONObject Data = response.getJSONObject("Data");
                    JSONObject AggregatedData = Data.getJSONObject("AggregatedData");

                    try {

                        String Price = AggregatedData.getString("PRICE");

                        String formatPrice = formatter.format(Math.round(Float.valueOf(Price)));


                        _price.setText("Price :" + formatPrice);


                    } catch (Error e) {
                        _price.setText("Data Not Avvaliable");

                    }


                try {

                    String Open = AggregatedData.getString("OPENDAY");
                    String formatOpen = formatter.format(Math.round(Float.valueOf(Open)));
                    _open.setText("Open :" + formatOpen);


                } catch (Error e) {
                    _open.setText("Data Not Avvaliable");

                }

                try {
                    String Low = AggregatedData.getString("LOWDAY");
                    String formatLow = formatter.format(Math.round(Float.valueOf(Low)));
                    _low.setText("Low :" + formatLow);


                } catch (Error e) {
                    _low.setText("Data Not Avvaliable");

                }

                try {
                    String High = AggregatedData.getString("HIGHDAY");
                    String formatHigh = formatter.format(Math.round(Float.valueOf(High)));
                    _high.setText("High :" + formatHigh);


                } catch (Error e) {
                    _high.setText("Data Not Avvaliable");

                }

                try {
                    String Volume = AggregatedData.getString("VOLUMEDAY");
                    String formatVol = formatter.format(Math.round(Float.valueOf(Volume)));
                    _volume.setText("Volume :" + formatVol);


                } catch (Error e) {
                    _volume.setText("Data Not Avvaliable");

                }


                try {
                    String LastUpdate = AggregatedData.getString("LASTUPDATE");
                    String convert = unix_time(Long.parseLong(LastUpdate));
                    _lastUpdate.setText("Last Update :" + LastUpdate);
                } catch (Error e) {
                    _lastUpdate.setText("Data Not Avvaliable");

                }

                try {
                    String TradeId = AggregatedData.getString("LASTTRADEID");
                    _tradeId.setText("Trade Id :" + String.valueOf(Math.round(Float.parseFloat(TradeId))));


                } catch (Error e) {
                    _tradeId.setText("Data Not Avvaliable");

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }



    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    requestQueue.add(jsonObjectRequest);

}

2 个答案:

答案 0 :(得分:0)

您可以通过使用界面来实现。请按照以下步骤操作,

首先在您的应用程序中创建界面,例如

public interface AsyncTaskListener {
    void onRequestCompleted(JSONObject result, Integer statusCode);
}

并在您要发出请求的活动中实现此接口,假设凌空类的对象是objVolley,那么您的请求将如下所示

    public class YourActivity extends AppCompatActivity implements AsyncTaskListener {
        public void priceDate(YourActivity.this, coin, YourActivity.this);
    }

然后像这样排球类和方法

    public class PostDataHelper {
        public void priceDate(Context contex, final String coin, final AsyncTaskListener asyncTaskListener) {
@Override
        public void onResponse(JSONObject response) {
               asyncTaskListener.onRequestCompleted(response, 200);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             asyncTaskListener.onRequestCompleted(response, 200);
        }
    });
      }
    }

希望这对您有所帮助,祝您编程愉快。

答案 1 :(得分:0)

您的截击代码已嵌入到您的活动代码中,因此创建界面没有太多优势。

您需要创建一个单独的类来处理截击请求。

public class VolleyRequest {
    VolleyCallback mResultCallback;
    RequestQueue mRequestQueue;

    public VolleyRequest(VolleyCallback resultCallback, Context context){
        mResultCallback = resultCallback;
        mRequestQueue = Volley.newRequestQueue(context);
    }

    public void cancelRequests(String TAG){
        if(mRequestQueue != null){
            mRequestQueue.cancelAll(TAG);
        }
    }

    public void volleyGetRequest(String url, final String TAG) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (mResultCallback != null) {
                    mResultCallback.onSuccess(response, TAG);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (mResultCallback != null) {
                    mResultCallback.onError(error, TAG);
                }
            }
        });
        jsonObjectRequest.setTag(TAG);
        mRequestQueue.add(jsonObjectRequest);
    }
}

然后创建一个接口类来处理回调

public interface VolleyCallback {
    void onSuccess(JSONObject response, String tag);
    void onError(VolleyError error, String tag);
}

然后在您的活动课程中

private void initvolley(){
        VolleyCallback volleyCallback = new VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response, String tag) {
                switch (tag){
                    //add response handling code here
                }
            }

            @Override
            public void onError(VolleyError error, String tag) {
                //handle error response here
            }
        };
        VolleyRequest volleyRequest = new VolleyRequest(volleyCallback, this);
        String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
        volleyRequest.volleyGetRequest(URL, request_tag/*Request tag incase you have multiple requests in same activity*/);
    }