Android Volley Tutorial

Volley is an android library released by Google that can make your life easier when dealing with network operations. In this blog post I will mention the main features of the library and show a few example usages, in particular, how to make a request, how to download images, and how to use the cache.

Features of Volley library

a) Automatically schedules the network requests

b) Supports request prioritization. This means that you can load content depending of priorities, for example the main content could have a high priority, but the images a low priority.

c) Provides transparent disk and memory cache that allows for quick reloading of data. Transparent cache means that the caller doesn’t have to know about the existence of the cache. That is, the cache is implemented automatically. You do, however, have the possibility to disable the caching.

d) Provides a good API for canceling requests. You can cancel a single request, or cancel requests depending on some filters.

Besides the great features that Volley comes with, you don’t have to use it for everything. Volley is great for RPC-style network operations that populate UI, a typical example would be loading thumbnail images into a ListView, but not very good for streaming operations like downloading a video or mp3.

Getting started with Volley

1. Clone the Volley project:
git clone https://android.googlesource.com/platform/frameworks/volley
2. Import the library into your project

The most frequent classes of Volley that you will work with are RequestQueue and Request, and ImageLoader when dealing with images loading.

RequestQueue is used for dispatching requests to the network. It is recommended to create it early and use it as a Singleton.
Request is the base class for creating network requests (GET, POST).
ImageLoader is a helper class that handles loading and caching images from remote URLs.

Step 1: VolleySingleton.java

As recommended, lets create first a Singleton class that will return on demand an instance of RequestQueue and one of ImageLoader.

public class VolleySingleton {

    private static VolleySingleton instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleySingleton(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);


            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }


    public static VolleySingleton getInstance(Context context) {
        if (instance == null) {
            instance = new VolleySingleton(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}
Step 2: Add internet permission
<uses-permission android:name="android.permission.INTERNET" /> 
Step 3: Create an instance of RequestQueue
RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();
Step 4: Create the request

Volley comes with a class called JsonRequest that you can use to make requests to a server that returns a json response.
However, in this example we will query an RSS feed which returns a response in XML format. Volley does not include a similar class for handling xml responses, like JsonRequest, but it has StringRequest class that can be used to retrieve the response body as a String.

There are two ways to construct a StringRequest:

StringRequest(int method, String url, Listener<String> listener,
            ErrorListener errorListener)

or

StringRequest(String url, Listener<String> listener, ErrorListener errorListener)

The second constructor does not take the request method as a parameter, when not specified, a GET request is created.

Listener is a callback interface for delivering the result, and
ErrorListener is a callback interface for delivering error responses.

Example:

String url = "http://www.pcworld.com/index.rss";
StringRequest request = new StringRequest(url, new Listener<String>() {

            @Override
            public void onResponse(String response) {
                // we got the response, now our job is to handle it 
                parseXmlResponse(response); 
            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
               //something happened, treat the error.
            }
        });
Step 6: Execute the request
queue.add(request);

And that is all! The execution of the request implies its addition to the RequestQueue.

Step 7: Loading thumbnail images

Loading images can be done easy if you replace the android’s ImageView with Volley’s NetworkImageView:

<com.android.volley.toolbox.NetworkImageView
        android:id="@+id/icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/default_placeholder" />

then use setImageUrl() and you are done!

String url = "..."; // URL of the image
ImageView imageView = (ImageView)view.findViewById(R.id.image);
ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageView.setImageUrl(url, imageLoader); 

If, for some reason, you don’t want or can’t use NetworkImageView, then there’s an alternate method.
You can use the get() method of ImageLoader class which accepts the image url and an instance of ImageListener:

ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageLoader.get(url, new ImageListener() {
             
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(R.drawable.icon_error); // set an error image if the download fails
            }
             
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    imageView.setImageBitmap(response.getBitmap());
                } 
            }
        });
Reading from cache

One of the Volley’s features is that it provides transparent disk and memory cache. The cache is implemented automatically for classes that extends Request, such as JsonRequest and StringRequest.

To read the cache:

Entry entry = queue.getCache().get(url);
if(entry!=null){
     String data = new String(entry.data, "UTF-8");
     // process data
}

To turn off the cache:

request.setShouldCache(false);

to remove the cache for a specific request:

queue.getCache().remove(url);

to clear all cache:

queue.getCache().clear();

to invalidate the cache: this will allow to display the cached data until the response is received. When the response is received, it will automatically override the cached data.

queue.getCache().invalidate(url, true);

For more details about Volley you can watch the full video at: https://developers.google.com/events/io/sessions/325304728

Amazing Cracked Screen

Hello everyone,

In this weekend I made a simple application just for fun – Amazing  Cracked Screen, the main purpose being to trick your friends and make fun of them! Basically, what does the application is to simulate a broken phone screen.
The application includes 6 different broken screens, and provides the ability to set up a delay time when the app should start, so you can manage to give the phone to your friend.

Just start the application, select the desired broken screen and have fun!

 

Amazing Cracked Screen

How to verify an RSS Feed if New Articles have been published.

Recently I built an rss app for a site that publishes daily IT News – ITMoldova.com. The main feature of application is to launch a service in background (at a given interval of time), and check if new articles have been published on http://itmoldova.com site. If it turns out that new articles have been published, then fire a notification message and notify the user about this, something like this: “4 New Articles Published on ITMoldova.com”.

How to identify how many articles were published?

The mechanism to identify if new articles have been published on the site (and how many) is pretty straightforward: when the application is installed and launched for the first time, it parses the Rss Feed and creates a new entry in the SharedPreferences with the value of <pubDate> element, of the first item from the rss list (pubDate = publication date). Then, everytime the service starts, it parses the RSS Feed and checks the value of first item from the rss list against the value stored in SharedPreferences, if the value stored in SharedPreferences is less than value returned by the service, then it means that there are new articles and it’s time to notify the user! Lastly, update the SharedPreferences with the most recent pubDate.

For the sake of simplicity and keeping things consistent, I will post here only snippets of most relevant code, but this will be good enough to give you an idea about how things works.

How to compare two dates?

To compare the dates we need to convert them to milliseconds. The getTime() method of Date class can help us return the number of milliseconds of a given date:

Date date=new Date();
int timeMilliseconds=date.getTime();

 

Below is the implementation of verifyDates(String, String) method that will be used by the Service. The method takes 2 string parameters, the pubDate of rss item, and the pubDate stored in SharedPreferences.


public class Tools {
  public int newArticles;
  public boolean hasMoreArticles = true;

  public void verifyDates(String rssPubDate, String sharedPrefLastPubDate) {
    if (hasMoreArticles) {
      SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
      Date dLastPubDate = null;
      Date dRssPubDate = null;

      try {
        dLastPubDate = df.parse(sharedPrefLastPubDate.substring(5));
        dRssPubDate = df.parse(rssPubDate.substring(5));
      } catch (ParseException e) {
        Log.d("GREC", "Exception in verifayDates: " + e.getMessage());
        e.printStackTrace();
      }

      //We want to count how many new articles were published.
      if (dRssPubDate.getTime() > dLastPubDate.getTime()) {
        newArticles++;
      } else {
        hasMoreArticles = false;
      }
    }
  }

}
The Service Implementation

The service will parse the Rss Feed and do the comparison. Also, it will launch a status bar notification if it turns out that new articles were published.

public class RssService extends IntentService {

  public RssService() {
    super("ITMoldovaRssService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {

    // Retrieve the date from SharedPreferences
    String lastPubDate = getDateFromSharedPrefs();

    // The AndroidFeedParser class helps us parse the Rss Feed.
    AndroidFeedParser parser;

    try {
      parser = new AndroidFeedParser(new URL("http://itmoldova.com/feed/"));
      List<Message> list = parser.parse();

      if (list != null) {
        for (int i = 0; i < list.size(); i++) {

          // Verify the pubDate of each item, against pubDate stored in SharedPreferences
          tools.verifyDates(list.get(i).getDate(), lastPubDate);
        }

        // Get the last pubDate and save it to SharedPreferences.
        lastPubDate = list.get(0).getDate();
        saveToSharedPreferences(lastPubDate);
      }
    } catch (MalformedURLException e) {
      Log.d("GREC", "Malformed URL Exception: " + e.getMessage());
      e.printStackTrace();
    }

    if (tools.newArticles > 0) {
      displayNotification();
    } else {
      Log.d("GREC", "No new articles ");
    }
  }
}

 

The service begins with parsing the Rss Feed and return the list of items:

List<Message> list = parser.parse();

then iterate through it comparing the publication date:

for (int i = 0; i < list.size(); i++) {
    // Verify the pubDate of each item, against pubDate stored in SharedPreferences
    tools.verifyDates(list.get(i).getDate(), lastPubDate);
}

and then ends getting the most recent publication date and saving it to SharedPreferences:

// Get the last pubDate and save it to SharedPreferences.
lastPubDate = list.get(0).getDate();
saveToSharedPreferences(lastPubDate);

If it turns out that new articles were published, display a status bar notification.

if (tools.newArticles > 0) {
displayNotification();
}

 

How to parse an XML feed and how to display a status bar notification are some helper topics you may need to take a look in order to fully complete this task.

How to simulate an incoming call in Android

1. Start the Android Emulator

2. Open up the windows console by going to Start -> Run (or Windows + R shortcut) and type in “cmd”. Press Enter. This should open the dos console.

3. Type in “telnet” and press enter. This should open the Telnet Console.
(At this stage you may experience some problems, the console may display the error: ‘telnet’ is not recognized as an internal or external command, operable program or batch file. If this is the case, scroll down to see how to fix it, then return and continue the process)

4. Telnet Console being displayed, type in “o localhost 5554″. This will establish a connection with the emulator on port 5554 and open the Android Console. 5554 is the port number and you can see it on the title bar of the emulator window.

5. To simulate the call, type in “gsm call 099062274”

6. To cancel the call, type “gsm cancel 099062274″

7. Use “exit” to exit the Android Console, and “quit” to quit the Telnet client.

That’s it!

android incoming call

*How to fix the: ‘telnet’ is not recognized as an internal or external command, operable program or batch file error.

When trying to invoke the telnet program you may experience the above error. The cause of this could be that the Telnet Client is turned off on your computer.

To turn it on, follow these steps:
1. Go to Control Panel

2. Click on Programs

3. Under Programs and Features section, click on Turn Windows features on or off. This should bring you the Windows Features pop-up.

4. Find the Telnet Client, select it, click OK.