-1

I know this is the answer, but I couldn't add it to my code.

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

like here I created interface. I did it all. I just don't know how to convert this my code to it, and how to use the return value in other activities.

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

}
sulox32
  • 419
  • 3
  • 19
Erzo
  • 103
  • 1
  • 3

2 Answers2

0

You can achieve this by using interface. Follow the below steps,

First create Interface in your application like,

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

And implement this interface in your activity where you want make request, Assume object of your volley class is objVolley, then your request will like below

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

Then Your volley class and method like 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);
        }
    });
      }
    }

Hope this will help you, Happy coding.

Mohanraj
  • 296
  • 2
  • 13
0

Your volley code is embedded into your activity code so there isn't much advantage to creating a interface.

You need to create a separate class for handling volley requests.

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

Then create a interface class to handle the callbacks

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

Then in your activity class

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*/);
    }
Arun
  • 321
  • 2
  • 8