Volley and AsyncTask
Asked Answered
R

4

49

I read a post about Volley and I know it's great networking library. But I couldn't understand one thing.

All requests are Async Task or not?

When I want to send asyncTask request using Volley do I need put Volley request in AsyncTask? or should I just call Volley Request if it is already AsyncTask request?

 private class MyClass extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
           // do Volley request
        }
}

Is this right approach?

Rossini answered 19/12, 2013 at 6:44 Comment(1)
It alreadyy happens in the background asynchronously. You *DO NOT need AsyncTaskAlto
B
65

You don't need to run Volley request on AsyncTask.

Why:

They manage all network related task on separate thread. If you look closely at library project they did not picture the AsyncTask. But they intelligently handle all network related task efficiently.

Check RequestQueue.java class in Volley's main package

here I am pasting java doc.

/**
 * A request dispatch queue with a thread pool of dispatchers.
 *
 * Calling {@link #add(Request)} will enqueue the given Request for dispatch,
 * resolving from either cache or network on a worker thread, and then delivering
 * a parsed response on the main thread.
 */

Edited:

Forming a Request:

With Volley, network communication is managed by the RequestQueue. The best way to utilize the RequestQueue and all of its tools, especially the cache, is by instantiating it once and keeping it around as a singleton. At this point you can then add or cancel requests, stop or start requests, and access the response cache(s).

RequestQueue queue =Volley.newRequestQueue(this);

Once the RequestQueue has been instantiated a request must be formed. This can be done utilizing a few different “out of the box” request classes included with the Volley Library or by extending Volley’s request class into your own custom request. The request classes already included in Volley are a String request, JSON requests, and an Image Request. Most of the request classes included in Volley library utilize constructors much like the one below.

Parameters being passed into constructor:

RequestMethod(get, post, delete, ect) JSONObject-An optional object that will be posted with your request ResponseListener- Where your data will go after the request is complete ErrorListener – What will be told when there was a problem with your request.

JsonObjectRequest request = JsonObjectRequest(Requestmethod, url, null,  new ResponseListener(), new ErrorListener());

Listners to receive response:

Successful Response Listener

private class ResponseListener implements Response.Listener{
  @Override
  public void onResponse(JSONObject response){

  }
}

Error Response Listener

private class ErrorListener implements Response.ErrorListener{
  @Override
  public void onErrorResponse(VolleyError error){

  }
}

Finally add your request to Request queue, rest of everything Volley will handle for you.

Making call:

Now, that we have made our request and response classes we are ready to add the request to the queue and retrieve the data. To do so we simply add the request to the queue.

queue.add(request);

The response or error will then be delivered to the response/error classes that we defined in our request. You can add as many requests to the queue that you would like at one time and the responses will be delivered to their respective response/error classes

Been answered 19/12, 2013 at 6:48 Comment(1)
I'm revisiting Android after a very long break (years) and I installed Android Studio, Googles official Android IDE. I setup a new project using the email/password login template, and the boilerplate code in the login activity included an AsyncTask where you're supposed to put your HTTP request. This confused me and it's what led me to this question. I'm assuming that Google doesn't intend for you to use Volley in this case?Mcavoy
B
6

When you use Volley, there's no need to combine it with AsyncTask. It does the networking stuff on another thread for you.

Here is a basic example of a network call using Volley. As you can see, all the code is just in the Activity, without any need to define an AsyncTask.

Builder answered 19/12, 2013 at 6:49 Comment(3)
Unfortunately the link in your answer is broken.Staminody
What if I upload an image, for my profile pic after registering. There is a sample youtube tutorial that he uses them both.Arriola
@FilipedeLimaBrito This is the reason why is better to include relevant code in the answer instead of a link that can broke in the future.Churchman
B
1

Volley cannot be inserted inside AsyncTask because,

Volley is initiating background thread(s) on its own so all the network requests are executed off the UI thread so primarily you don't need to extend AsyncTask anymore. Of course you will have to take care to cancel the running requests on rotation or when user exits your activity.. As Volley is mainly used for minor Networking purposes in Android (for major use DownloadManager). It does similar working of AsyncTask Class. Implement Singleton in Volley. Images can also be sent in Volley.

Badman answered 21/2, 2017 at 12:27 Comment(0)
D
0

The whole point of introducing Volley library was to make sure user doesnt have to worry about all the "obvious" stuff while sending a network request. This means that volley takes care of the following on its own

  • Switching Background thread
  • Transparent disk and memory response
  • Multiple concurrent network connections. etc

To answer your question- You don't need to worry about switching to background thread, Volley takes care of this on its own. Also once the request is completed the success or failure callback is invoked on the main thread.Hence with Volley developer need not worry about switching threads

This tutorial here gives a good step by step explanation of Working with Volley Library

Divider answered 3/5, 2018 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.