I decided to give Volley a try, so presently I have a lot of REST callouts to be done, so I usually create a RequestHandler and a ResponseHandler class which as their names suggest handle requests and responses respectively. I follow this pattern so that I don't write redundant code. I just pass in the dynamic query/url as parameter and using a switch case handle the response to each of the requests. But I am stuck with the below problem :
I have no way of updating my UI thread from where I call the RequestHandler class. What I have tried or already know so far :
I was wondering, how you guys do it? Is there any pattern better than the Request/Response Handler pattern I follow? Any way of updating the UI thread following the same pattern?
Thanks in advance !
We use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue manages the worker threads and makes the network calls in the background. It also takes care of writing to cache and parsing the response. Volley takes the parsed response and delivers it to the main thread.
All the tasks that need to be done with Networking in Android, can be done with the help of Volley. Automatic scheduling of network requests. Multiple concurrent network connections. Canceling request API. Request prioritization. Volley provides debugging and tracing tools.
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle (app) and add the below dependency in the dependencies section. After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Start by including Volley in your Android project. The easiest way to add Volley to your project is to add the following dependency to your app’s build.gradle file. Another way to do this is by cloning the Volley repository.
I use volley, and this is what I do. The code goes anywhere in your activity.
import com.android.volley.Response.Listener;
import static com.android.volley.Response.ErrorListener;
Listener<YOURDATACLASS> successListener = new Listener<YOURDATACLASS>() {
@Override
public void onResponse(YOURDATACLASS data) {
// Check to make sure that the activity hasn't been destroyed while the call was in flight.
if (! isFinishing()) {
//DO YOUR UI UPDATE, such as
TextView textview = (TextView) findViewById(R.id.yourtextview);
textview.setText("blah blah blah");
}
}
};
ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//DO SOMETHING ON FAILURE
}
YOURAPICALL(successListener, failurelistener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With