About Francesco Azzola

I'm a senior software engineer with more than 15 yrs old experience in JEE architecture. I'm SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. I'm an android enthusiast and i've worked for long time in the mobile development field.

Android Volley Tutorial: Post and download image

In this post, I want to describe how to use a very powerful and easy to use library for Android. This library is called Volley and it can be used to handle networking connection. In previous post, we talked about HttpUrlConnection and Apache HTTP client. They are both valid and useful but using Volley we can simplify our work. Volley is a library and we can download it using git: git clone

Once we get the code, we can build up our project. If you notice the code you download is meant for Android Studio. If you want to move it to Eclipse it is very simple. Don’t forget to set the project as library.

Why use Volley?

Well we may ask why we need to use another library if we have already everything we need to handle network connection (i.e Http connection). Well, if you read the previous posts, we have noticed we have some work to do: for example we have to create an AsyncTask, handle the network connection erorrs and so on. Volley simplify everything and increases the app performances. Volley gives us:

  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs

These points are enough to chose Volley as our base networking library. In this post, I will show some basic operations with Volley while in some other posts I will show some other more “complex” operation.

Volley core

When we use Volley there are some classes that play an important role and most probably they are the classes we will use more often. These classes are:

  • RequestQueue
  • Request
  • Response
  • Some useful class that simplify our work (toolbox package)

RequestQueue is the core class of Volley lib, it handles all the requests we make in our app. It takes care of queuing the requests and handle the responses. Usually we create an instance of this class calling:

RequestQueue rq = Volley.newRequestQueue(this);

This code line simply creates a RequestQueue instance with default parameters. If we want to have more control, we can instantiate this class directly. Once we have our request queue instance, we can add our requests. Network requests are instances of Request class. Usually we have everything we need under the toolbox package, but we can always customize our request extending Request class and providing our logic. Response class is the class we use when we want to listen to the response data or to the error events.

We will see it in more detail later. If we don’t have special needs, we can use some classes in the toolbox package. These classes helps us handling common request: string request and image request for example.

Post request

One of the most common request we usually make is the POST request, where we send some parameters to a remote server. In this scenario we can use a StringRequest because we expect to send data string and receive a string response. So we have:

RequestQueue rq = Volley.newRequestQueue(this);
StringRequest postReq = new StringRequest(Request.Method.POST, "http://httpbin.org/post", new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        tv.setText(response); // We set the response data in the TextView
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        System.out.println("Error ["+error+"]");

    }
}) ;

At line 1, we create a request queue handler. At line 2, we instantiate the StringRequest. You can notice that the code seems a bit too complex, but it is very simple. The first thing we specify that this request is a POST request, then the destination url (http://httpbin.org).  Looking at the code, you can notice we have two different listener:

  • Response.Listener
  • Response.ErrorListener

The first one, is called when the response is received and is ready. In this case the onResponse method is called. This method runs in the main thread so we can update, for example, some UI wigtes. If something goes wrong, the ErrorListener.onErrorResponse is called. In this method, we have the chance to handle the error and notify it to the user.

Until now, we didn’t send any parameter. If we want to post some data to a remote server we have to override getParams method. In the Request class, getParams is a method that returns null. If we want to post some params, we have to return a Map with key value pair. In this case, we can override this method:

RequestQueue rq = Volley.newRequestQueue(this);

StringRequest postReq = new StringRequest(.....)  {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();

        params.put("param1", param);
        return params;
    }

};

In this case, we create a key called param1 and pass the value stored in param parameter. At the end, we need to add our request to the request queue.

rq.add(postReq);

Running the code, we have:

android_volley_post4

Download binary data: Image

What about if we want to download binary data? Well if we want to download, an image, from a remote server, we can use the ImageRequest. In this case, we have:

ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() {

    @Override
    public void onResponse(Bitmap response) {
        iv.setImageBitmap(response);

    }
}, 0, 0, null, null);

As before, in the onResponse method we set the image we receive from the remote server (line 4). We could set the image width and height and other parameters. In this case, we didn’t implement the error listener. In this case we have:

android_volley_download_image9

Custom request

As said, we can extend the base Request class, so that we can implement our logic. In this case we to override two methods:

  • parseNetworkResponse
  • deliverResponse

In the first method, we have to extract the data from the response while in the other one we notify the response. We will cover these aspects in some other posts.

  • Source code available soon.

 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


− 2 = four



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close