0

I am sending a simple request using Volley everything is fine but after the networking code, some part of code is not executed.
Here's the code:

private String sendMessage(String paymentId){

        final StringBuilder response = new StringBuilder();

        //url
        String url = "testUrl";

        //Simple Request
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String res) {
                        Log.d("pay","MesaageID :"+res);
                        response.append(res);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("pay",""+error.toString());
            }
        });

        //This Log.d statement is not executed.
        Log.d("test","working!"+response.toString());
        queue.add(stringRequest);
        return response.toString();
    }
Raunak Pandey
  • 371
  • 2
  • 16
  • 1
    "...after the networking code, some part of code is not executed." – If you're expecting the `"working!"` log to come after the `"MesaageID :"` log, that's not how it'll happen. That `StringRequest stringRequest` is code that runs later, when the Volley request has completed. That request doesn't even start until `queue.add(stringRequest);`. I'm assuming you did this to figure out why it's returning an empty `String`. You cannot return any of the expected results from your `sendMessage()` method like that. You need to execute whatever code needs those results at the end of `onResponse()`. – Mike M. Jun 19 '20 at 04:53
  • @MikeM. omg, thanks for pointing out my mistake also I want the response string in my outer class how can I do that? – Raunak Pandey Jun 19 '20 at 09:34
  • 1
    I'm not quite sure what you mean by outer class. If that code is indeed in an inner class of the class that ultimately needs the Volley results, then you should be able to use them directly; e.g., if that's in `MainActivity`, you could just call `textView.setText(res);` in `onResponse()`. If that's actually in a separate, or `static`, class, then you could set up a basic interface callback, something like is shown in [this answer](https://stackoverflow.com/a/28120209). – Mike M. Jun 19 '20 at 09:50
  • 1
    @MikeM.Thankyou so much :) – Raunak Pandey Jun 19 '20 at 14:07

0 Answers0