Image downloading and caching with Picasso Library

Picasso Library is very powerful tool for avoiding Bitmap handling in your application. It takes care of displaying image efficiently in ImageView from local sdcard, network or application resource. All of this can be done in single line of code.

If you are a self-do android programmer, you will take care of same task writing several lines of code.

1. Using AsyncTask for downloading images in background.

2. In addition to background thread, you will keep track of downloads for particular ImageView in order to handle orientation change or if user scrolls your list/grid view.

3. To avoid downloading image, you would prefer to have cache for your downloaded bitmaps. You will implement LRUCache<String, Bitmap> for smooth caching of downloaded images.

Picasso library provides you power to handle all of the above task with just single line of code. It will take care of following functionalities by itself.

1. Handling ImageView recycling and download cancellation in an adapter.

2. Complex image transformations with minimal memory use. You can resize your bitmaps to fit nicely in your ImageView without any hassle.

3. Automatic memory and disk caching.

Sample Picasso Application

1. Add gradle dependency in build.gradle file.
compile ‘com.squareup.picasso:picasso:2.5.2’

2. Add Internet permission in application manifest file since we will load image from network as well.
<uses-permission android:name=”android.permission.INTERNET”/>

3. Prepare your layout view for showing images loaded by Picasso. I have taken 3 ImageViews to show loading images from network, application resource and sdcard. Modify your /res/layout/activity_main.xml as below.

4. In our java source code of activity, we will take references of ImageView’s in layout file. For these views, we will load images in single line of code. Refer setImagesUsingPicasso() for details. Make sure you have placed one png file named “picasso_demo_image.png” in sdcard root directory. Otherwise it will show error image as specified.

5. Build and run your application. You will observe images loaded into your views.

Picasso perform efficient bitmap transformation. You can define height, width and scale type for better fit in your view.

Picasso also supports PlaceHolder images. In case of error in download, it will try for total of 3 times and finally error placeholder will be shown.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *