Danial
Danial

Reputation: 622

volley return from inner class

I have successfully created a server to serve me API. As my server has many API and I want to use them on my android project, so I am writing a two method for my Android application.

One is for get, this method will handle all sort of GET requests.

public static JSONObject postData(final Context context, String path, Map data)
{

    final RequestQueue requstQueue = Volley.newRequestQueue(context);
    String url=Util.serverURL+path;

    JSONObject res=null;

    JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST,url ,new JSONObject(data),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                res=response;
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
            }
        }
    ){

    };
    requstQueue.add(jsonobj);
}

Here is the problem it can't return the response.

How can I return the response from inner class ?

Assigning the res gives me error. And how should I return so that using async I can receive that?

Upvotes: 0

Views: 48

Answers (1)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15433

You can't get response from asynchronous operation like this. You have to use callback function to get result when asynchronous operation complete. Follow below steps:

  • Create an interface for callback
interface VolleyResponseListener {
    void onComplete(JSONObject jsonbject);
}
  • Configure your postData to handle this callback
public void postData(final Context context, String path, Map data, VolleyResponseListener callback) {

    ....
        @Override
        public void onResponse(JSONObject response) {
            callback.onComplete(response);
        }

    ....
}
  • Implement this interface in your activity or fragment
postData(..., new VolleyResponseListener() {
    @Override
    public void onComplete(JSONObject jsonbject) {
        //you can use jsonbject here
    }
});

Upvotes: 1

Related Questions