Reputation:
I am using volley library for API calls and getting response. But i want to wait for getting complete response from API then execute rest of code below Volley request. I tried it using interfaces and also using thread but it is not working.
Please give me some suggestion for implementing this? Thanks.
Upvotes: 0
Views: 1236
Reputation: 11474
As you sending request in volley, It will call you back if request is successful or any error occurred :
So You need to call a method that contains code that should be executed after getting response :
Here I have commented where you can call that method :
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, js, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Successfully signed in : " + response.toString());
//put your code here
// added method call
parseJson();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String json = null;
Log.e(TAG, "Error at sign in : " + error.getMessage());
// put your code here
}
});
Edited :
For executing code after json parsing :
Handler : IncomingHandler
class
private static class IncomingHandler extends Handler {
private WeakReference<MainActivity> yourActivityWeakReference;
public IncomingHandler(MainActivity yourActivity) {
yourActivityWeakReference = new WeakReference<>(yourActivity);
}
@Override
public void handleMessage(Message message) {
if (yourActivityWeakReference != null) {
MainActivity yourActivity = yourActivityWeakReference.get();
switch (message.what) {
case 0:
// add your code here
break;
}
}
}
}
Create instance of it in onCreate()
// Declaration of handler
private IncomingHandler incomingHandler;
// initialize handler
incomingHandler=new IncomingHandler(MainActivity.this);
Sample parse json method and sending message using handler :
public void parseJson() {
for (int i = 0; i < 50; i++) {
System.out.println("Printing :" + i);
}
incomingHandler.sendEmptyMessage(0);
}
Thanks.!!
Upvotes: 1