Android Picasso Library Tutorial With Example

Android Picasso library is a powerful android library, built by square, for image downloading and caching. It’s very simple to use and you need to write just a few lines of code to do the job.

In this tutorial, you will learn how to use android Picasso library for image downloading and caching. After that, you will learn some advance concepts about this library. For example, you will learn how to use picasso library to show placeholder while image is being downloaded, how to show error image if error occurs while image is being downloaded etc.

Output

tutotialwing  android picasso library output

Tutorialwing – android picasso library tutorial output

Video Output

Getting started

There are 2 sections in this tutorial. First section contains an example to show how to use Picasso library. Second section contains some advance concept about Android Picasso library.

1. How to use Android Picasso Library ?

This section will answer the question “How to use Picasso library?”.

1.1 Creating new Project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as PicassoLibrary and click next.
b. Select Minimum SDK 16 –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully. You will get folder structure like below.

Tutorialwing - android picasso tutorial folder structure

Tutorialwing – Picasso tutorial folder structure

1.2 Add gradle for Picasso library in app/gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    compile 'com.squareup.picasso:picasso:2.5.2'    //gradle for picasso.
}

1.3 Add internet permission in AndroidManifest.xml

Since you are going to do network operations you need to add internet permission in your AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="tutorialwing.com.picassolibrary"
          xmlns:android="http://schemas.android.com/apk/res/android">

    //internet permission.
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

1.4 Add ImageView in activity_main.xml

For the sake of simplicity, we are going to download and show image in an imageView. So, go to activtiy_main.xml file and add ImageView in it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="tutorialwing.com.picassolibrary.MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

1.5 Add code to load image in ImageView

Go to MainActivity.java file and add the code to load image into imageView using Picasso library.

package tutorialwing.com.picassolibrary;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {

	ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		imageView = (ImageView) findViewById(R.id.imageView);

		Picasso.with(this)  //Here, this is context.
			.load("http://i.imgur.com/DvpvklR.png")  //Url of the image to load.
			.into(imageView);
	}
}

1.6 Output

Run the app. You will see output as shown above in this post.
Congratulations! you just used Android Picasso library to download and load image into imageView.




2. Advance concepts about Android Picasso Library

This section contains some advance concepts about Picasso library.

2.1 Load Specific image

You can load a specific image using this library. You just need to provide the exact path of the image. For example –
If you want to display images from res/drawable folder, you just write R.drawable.image-name in load(..) method.

Picasso.with(context)
	.load(R.drawable.image_name)  //name of the image to load.
	.into(imageView);

or If you want to display image stored in some other file, you just need to write path to that image into load(..) method.

Picasso.with(context)
	.load("file:///android_asset/image_name.png")  //path of the image stored in file.
	.into(imageView);

Picasso.with(context)
	.load(new File(...))  //File of the image to load.
	.into(imageView);

2.2 Show placeholder image using Picasso library

If you want to show placeholder while loading original image, you can do as below.

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.placeholder_image_name.png) // Write path to placeholder image.
    .into(imageView);

2.3 Show error image using Picasso library

If you want to show image when error occurs while image is being downloaded, you can do it as below.

Picasso.with(context)
    .load(url)
    .error(R.drawable.error_image_name.png) // Write path to image you want to show
    .into(imageView);

2.4 Fit image into View using Picasso Library

If you want to transform image to better fit into view or reduce memory size by resizing image, you can do it as below.

Picasso.with(context)
  .load(R.drawable.image_name.png)
  .resize(60, 60) //resizing width and height of image
  .centerCrop()  // transform image.
  .into(imageView)

2.5 Re-use property of Picasso library

Another important feature of this library is that it automatically detect adapter re-use and cancels the previous request.

@Override public void getView(int position, View convertView, ViewGroup parent) {
  ImageView view = (ImageView) convertView;
  if (view == null) {
    view = new ImageView(context);
  }
  String url = getItem(position);

  Picasso.with(context).load(url).into(view);
}

Notice here that ImageView is created once and then re-used. So, Each time it is re-used, previous download request is cancelled and new request is sent. This is very important feature as you don’t need to bother about request cancellation when using this library in adapter.

2.6 Know from where image is loaded into view

For development purposes, If you want to see whether image is loaded from disk, memory or downloaded from internet, you use setIndicatorsEnabled(true) on the Picasso instance. It will show Red, Blue or Green symbol on left corner of the view. Meaning of different colors are written below.

Red : Image is downloaded from internet.
Blue: Image is loaded from Disk i.e. disk caching.
Green: Image is loaded from memory i.e. memory caching.



3. Glide Library vs Picasso Library

You may be confused which is better Glide library or Picasso library. Followings are some comparisons between two libraries.

3.1 Glide and Picasso both are on jcenter.

Both libraries are on jcenter. You can import these libraries into your project as below.
Picasso

dependencies {
    compile 'com.squareup.picasso:picasso:2.5.2'
}

Glide
Glide also needs android support library v4.

dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.4.0'
}

3.2 The way to load image

The way to load image into ImageView is similar in both. But Picasso accepts only Context in with() method in Picasso.with(…..).into(imageView) while Glide accepts Context, Activity and Fragment as well. Benefit of passing Activity/Fragment is that image loading would be integrated with Activity/Fragment’s lifecycle. e.g. Image loading can be paused on pause state, resume on resume state of Activity/Fragment etc.

3.3 Bitmap format

Glide’s default bitmap format is set to RGB_565 so image quality will be poorer compared with Picasso. But the advantage is that it will consume less memory. If you are ok with image quality, don’t change the bitmap format else change it to ARGB_8888 as below.

package tutorialwing.com.glidelibrarytutorial;

import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.module.GlideModule;

public class GlideConfiguration implements GlideModule {

	@Override
	public void applyOptions(Context context, GlideBuilder builder) {
		// Change bitmap format to ARGB_8888
		builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
	}

	@Override
	public void registerComponents(Context context, Glide glide) {
		// register ModelLoaders here.
	}
}

Then, Add meta-tag into AndroidManifest.xml

<meta-data android:name="tutorialwing.com.glidelibrarytutorial.GlideConfiguration"
           android:value="GlideModule"/>

If you run the app, images will look better now.

3.4 Image caching

Glide creates cached images per size while Picasso saves the full image and process it. Means If you are trying to load image(500 x 500) into imageView (200 x 200). Glide will download full image, then resize it to 200 x 200, then it will cache and load into imageView while Picasso will download full image then it will cache full image then resize it to 200 x 200 and load it into imageView.
Next time when you request same image(500 x 500) to load into imageView(100 x 100) , Glide will again download the full image(500 x 500) then resize it to 100 x 100 then cache and load into imageView. Picasso, unlike Glide, picks up the cached full size image and resize and load it into imageView(100 x 100). Picasso doesn’t download same image again.

However, you can configure Glide to cache Full Size and Resized image as below.

Glide.with(this)
     .load(“IMAGE URL HERE”)
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .into(imageView);

3.5 Structure/Design

Glide is designed in such a way that it loads and shows image very fast.

You can learn more about glide library in Android Glide Library post.

Based on the above differences , you can choose any library. If you want to save more memory, you can opt for Picasso library. But if you want to show images faster you need to choose Glide library.

Conclusion

Android Picasso Library is a simple, easy to learn and use, yet powerful android library for image downloading and caching. You can load image from anywhere very easily. You just need to provide the path to that image. You can also check whether image is being loaded from cache or hard disk or server. Hope this tutorial helped you.

3 Comments

  1. Tutorialwing June 19, 2016
  2. avis August 16, 2016
    • Tutorialwing August 20, 2016

Leave a Reply