Tyson Tyson - 1 year ago 47
Android Question

Handle callbacks in my library

I have written an android library that does network calls to various websites and returns the necessary content. I am using Volley library which has callbacks like

onResponse
and
onFailure
. Initially this library was an app and was later changed to an library.

When it was an app I could handle the callbacks easily. Whenever the callback happens I call the required functions from there but now when I import as the library and try to use it the control returns from the library as soon as I call it and the call back is not doing anything.

public void sendForVerification(final String Response, final String Secret, final String Name) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
flag = true;
},
new Response.ErrorListener() {
@Override
public void onErrorResponse (VolleyError error){
flag = false;
}
}}) {
@Override
protected Map<String, String> getParams () throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("secret", Secret);
params.put("response", Response);
return params;
}
};
requestQueue.add(stringRequest);
}
}


When this code was a part of the app instead of returning the flag value I would call an appropriate function to handle the result. Now whenever I call these functions the value of flag is returned before the callback is done and this is causing some problem.

My question is how can I warp this around a callback so that the app that uses this library will be notified when the network call is done?

Answer Source

You could add your own callback(s) for your library

interface YourCallback<T> {
    onResponse(T value);
}

public void sendForVerification(final String Response,final String Secret,final String Name, YourCallback<Boolean> callback){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            callback.onResponse(true);
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            callback.onResponse(false);
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String,String> params = new HashMap<>();
            params.put("secret",Secret);
            params.put("response",Response);
            return params;
        }
    };
    requestQueue.add(stringRequest);
}

boolean flag;

api.sendForVerification("", "", "", new YourCallback<Boolean>() {
    @Override
    public void onResponse(Boolean value) {
        flag = value;
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download