Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a proper Volley Listener for cross class Volley method calling

I aim to call Volley from another class in, a very succinct, modular way ie:

            VolleyListener newListener = new VolleyListener();
            VolleySingleton.getsInstance().somePostRequestReturningString(getApplicationContext(), newListener);
            JSONObject data = newListener.getResponse();

But am having allot of trouble getting the listener portion to work so as to be able to access the resulting data from a method such as

newListener.getResponse();

There are a few questions on this site that generally outline how to set up a volley call from another class, such as: Android Volley - How to isolate requests in another class. I have had success getting the method call to work, but to now get that data into the present class for usage has caused trouble.

I have the action within my VolleySingleton class as:

public void somePostRequestReturningString(final Context context,final VolleyListener<String> listener) {

        final String URL = "http://httpbin.org/ip";

        JsonObjectRequest set = new JsonObjectRequest(Request.Method.GET, URL, ((String) null),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        listener.outPut = response.toString();
                        //Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", error.toString());
                    }
                }
        );

        mRequestQueue.add(set);
}

and within the listener class:

public class VolleyListener {
    public static String outPut;

    private static Response.Listener<String> createSuccessListener() {
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                outPut = response;
            }
        };
    }
}

How can I configure this to work and allow Volley calls and data retrieval from another class, particularly how to build callbacks correctly?

like image 632
Sauron Avatar asked Nov 05 '15 02:11

Sauron


People also ask

How to call API in Android using Volley?

To use volley with your android application first add dependency to your build. gradle(app level). Then we will create an interface, say FetchDataListener to use it as listener. We will use it's methods as callback while calling API request using volley.

How to use Volley in Android java?

Android App Development for Beginners This example demonstrate about How to use simple volley request in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How to GET Volley in Android Studio?

Understanding RequestQueue & Working With Volley In Android: To use it, first you need to instantiate the RequestQueue and later on you can start or stop request, add or cancel request and access the response cache(s). RequestQueue queue = Volley. newRequestQueue(this);


1 Answers

For your requirement, I suggest you refer to my following solution, hope it's clear and helpful:

First is the interface:

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(Object response);
}

Then inside your helper class (I name it VolleyUtils class):

public static void makeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    listener.onResponse(response);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    listener.onError(error.toString());
                }
            }) {

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                return Response.success(new JSONObject(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    };

    // Access the RequestQueue through singleton class.
    VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}

Then, inside your Activity classes, you can call like the following:

VolleyUtils.makeJsonObjectRequest(mContext, url, new VolleyResponseListener() {
        @Override
        public void onError(String message) {

        }

        @Override
        public void onResponse(Object response) {

        }
    });

You can refer to the following questions for more information (as I told you yesterday):

Android: How to return async JSONObject from method using Volley?

POST Request Json file passing String and wait for the response Volley

Android/Java: how to delay return in a method

like image 145
BNK Avatar answered Oct 26 '22 11:10

BNK