Android: How to return async JSONObject from method using Volley?
For your comment
I think that async is provided by Volley automatically. So i need to know how to get JSON data into the first snippet
IMO, instead of your first snippet, you can try the following way (of course, you can replace JSONArray
request by JSONObject
request):
VolleyResponseListener listener = new VolleyResponseListener() {
@Override
public void onError(String message) {
// do something...
}
@Override
public void onResponse(Object response) {
// do something...
}
};
makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);
Body of makeJsonArrayRequest
can be as the following:
public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
JSONObject jsonRequest = null;
try {
...
if (requestBody != null) {
jsonRequest = new JSONObject(requestBody);
}
...
} catch (JSONException e) {
e.printStackTrace();
}
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
listener.onResponse(jsonArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
});
// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
VolleyResponseListener
interface as the following:
public interface VolleyResponseListener {
void onError(String message);
void onResponse(Object response);
}