Reputation: 622
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
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:
interface
for callbackinterface VolleyResponseListener {
void onComplete(JSONObject jsonbject);
}
postData
to handle this callbackpublic void postData(final Context context, String path, Map data, VolleyResponseListener callback) {
....
@Override
public void onResponse(JSONObject response) {
callback.onComplete(response);
}
....
}
postData(..., new VolleyResponseListener() {
@Override
public void onComplete(JSONObject jsonbject) {
//you can use jsonbject here
}
});
Upvotes: 1