Click here to Skip to main content
15,881,803 members
Articles / Mobile Apps / Android

Android Picasso Tutorial Using Picasso Android Library

Rate me:
Please Sign up or sign in to vote.
4.58/5 (7 votes)
1 Nov 2016CPOL5 min read 9.7K   5  
In this post, we will discuss how to use picasso in Android studio to download images over network by creating a Picasso Android app.

In this post, we will discuss how to use picasso in Android studio to download images over the network by creating a picasso Android app. We will create a Movie App where we will show popular movies in GridView. We will also have functionality for adding or removing the movie as favorite.

Picasso Android Library offers an easy way to download and cache images in your Android app. Picasso Android Library is open source and widely used by Android developers as their favorite image downloader in apps. Check out the demo video below, you can click on download now button to download the full source code for this app.

So let’s discuss some of the pros and cons of Picasso Android Library.

  1. To download an Image, all you need to write is these five magical lines.
    Java
    Picasso.with(mContext)
        .load(movie.getImageUrl())
        .placeholder(R.drawable.ic_placeholder)
        .error(R.drawable.ic_error)
        .into(imageView);
    
  2. No need to create a singleton for image downloading purpose as required for Android Volley
  3. Automatic Handling of Memory and disk caching logic as well
  4. Support for image post processing like resizing and rotation of the downloaded image using simple commands
  5. Support for Request cancellation and parallel downloading

In this Android Picasso Tutorial, we will create an app that will have Picasso Android Library download the images from network and show them in a GridView, after resizing them.

Let’s get started.

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the firebase console.
  3. Choose project location and minimum SDK and on the next screen, choose Empty Activity, since we would be adding most of the code ourselves. Then click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, otherwise we have to generate it ourselves. Then click on Finish. We have used the default Activity Name MainActivity.

Gradle will configure your project and resolve the dependencies, Once it is complete, proceed to the next steps.

How to Use Picasso in Android Studio?

Adding Picasso library for Android studio is really simple, just add one dependency:

  1. Now open your project’s build.gradle from the project’s home directory and add the following dependency.

    build.gradle

    Java
    compile 'com.squareup.picasso:picasso:2.5.2'
    
  2. Since we need to connect to the network add the Internet permission in AndroidManifest.xml file.
    XML
    <uses-permission android:name="android.permission.INTERNET"/>

    Now, click on sync and gradle will syncronize and add picasso library for Android studio.

Adding Functionality

MovieAdaptor.java

Java
package com.androidtutorialpoint.picassoandroidtutorial;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

public class MovieAdapter extends BaseAdapter {

        private final Context mContext;
        private final Movie[] movies;

        public MovieAdapter(Context context, Movie[] movies) {
            this.mContext = context;
            this.movies = movies;
        }
        @Override
        public int getCount() {
            return movies.length;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Movie movie = movies[position];
        if (convertView == null) {
            final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            convertView = layoutInflater.inflate(R.layout.movie_layout, null);
        }
        final ImageView imageView = 
        (ImageView)convertView.findViewById(R.id.imageview_cover_art);
        final TextView nameTextView = 
        (TextView)convertView.findViewById(R.id.textview_movie_name);
        final ImageView imageViewFavorite = 
        (ImageView)convertView.findViewById(R.id.imageview_favorite);

        Picasso.with(mContext)
                .load(movie.getImageUrl()) //Load the image 
                .placeholder
                (R.drawable.ic_placeholder) //Image resource that act as placeholder
                .error(R.drawable.ic_error) //Image resource for error
                .resize(300, 500)  // Post processing - Resizing the image
                .into(imageView); // View where image is loaded.

        nameTextView.setText(movie.getName());
        imageViewFavorite.setImageResource(
                movie.getIsFavorite() ? R.drawable.ic_favorite : R.drawable.ic_not_favorite);
        return convertView;
    }
}

In the getView, we are inflating the movie_layout and then returning the view for the grid by setting the Image for the movie, setting the favorite icon and the movie name.

Note the use of Picasso for downloading the image. With few lines of code, we are loading the image and then resizing it to the required dimensions. We haved added two Image resources. The Placeholder is the image shown to the user while the image is downloaded from the network. You can observe this in our demo video, while downloading, we can see the placeholder image momentarily. The Error image is shown to the user, if there was some error while loading the image. You can check this by providing an invalid URL for the image.

  1. We will use a Java Model class Movie.java for this app. So create a new Java class Movie.java and add the following code.

    Movie.java

    Java
    package com.androidtutorialpoint.picassoandroidtutorial;
    
    public class Movie {
        private String name;
        private boolean isFavorite = false;
        private String imageUrl;
    
        public Movie(String name, String imageUrl) {
            this.name = name;
            this.imageUrl = imageUrl;
        }
    
        public String getName() {
            return name;
        }
        public boolean getIsFavorite() {
            return isFavorite;
        }
        public void setIsFavorite(boolean isFavorite) {
            this.isFavorite = isFavorite;
        }
    
        public void toggleFavorite() {
            isFavorite = !isFavorite;
        }
        public String getImageUrl() {
            return imageUrl;
        }
    }
  2. Next add a GridView to your activity_main.xml to show the images:

    activity_main.xml

    XML
    <?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:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.androidtutorialpoint.picassoandroidtutorial.MainActivity">
        <GridView
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:columnWidth="100dp"
            android:numColumns="auto_fit"
            android:verticalSpacing="24dp"
            android:horizontalSpacing="10dp"
            android:stretchMode="spacingWidth"
            />
    </RelativeLayout>
  3. Next, we create a Layout to represent our Movie Object in the GridView layout. Create a new layout resource file movie_layout.xml and put the following code.

    movie_layout.xml

    XML
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"    >
        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/imageview_cover_art"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="centerCrop"/>
            <ImageView
                android:id="@+id/imageview_favorite"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ic_not_favorite"
                android:layout_gravity="bottom|right"/>
        </FrameLayout>
        <TextView
            android:id="@+id/textview_movie_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:textStyle="bold"
            android:paddingTop="4dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:gravity="center_horizontal"/>
    </LinearLayout>

    This layout has three components:

    1. An ImageView for the Movie Poster
    2. An ImageView for a favourite icon
    3. A TextView for the Movie name
  4. Display the Movies in the grid, we will create a MovieAdapter class. It will act as data provider for the GridView. The adapter acts as the mediator between the GridView and the data by loading the Movies in the grid from the movie array that we will create. Create the java class MovieAdapter.java and add the following code.

    MovieAdaptor.java

    Java
    package com.androidtutorialpoint.picassoandroidtutorial;
     
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
     
    import com.squareup.picasso.Picasso;
     
    public class MovieAdapter extends BaseAdapter {
     
            private final Context mContext;
            private final Movie[] movies;
     
            public MovieAdapter(Context context, Movie[] movies) {
                this.mContext = context;
                this.movies = movies;
            }
            @Override
            public int getCount() {
                return movies.length;
            }
            @Override
            public long getItemId(int position) {
                return 0;
            }
     
            @Override
            public Object getItem(int position) {
                return null;
            }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final Movie movie = movies[position];
            if (convertView == null) {
                final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
                convertView = layoutInflater.inflate(R.layout.movie_layout, null);
            }
            final ImageView imageView = 
            (ImageView)convertView.findViewById(R.id.imageview_cover_art);
            final TextView nameTextView = 
            (TextView)convertView.findViewById(R.id.textview_movie_name);
            final ImageView imageViewFavorite = 
            (ImageView)convertView.findViewById(R.id.imageview_favorite);
     
            Picasso.with(mContext)
                    .load(movie.getImageUrl()) //Load the image 
                    .placeholder
                    (R.drawable.ic_placeholder) //Image resource that act as placeholder
                    .error(R.drawable.ic_error) //Image resource for error
                    .resize(300, 500)  // Post processing - Resizing the image
                    .into(imageView); // View where image is loaded.
     
            nameTextView.setText(movie.getName());
            imageViewFavorite.setImageResource(
                    movie.getIsFavorite() ? 
                    R.drawable.ic_favorite : R.drawable.ic_not_favorite);
            return convertView;
        }
    }

    In the getView, we are inflating the movie_layout and then returning the view for the grid by setting the Image for the movie, setting the favorite icon and the movie name.

    Note the use of Picasso for downloading the image. With few lines of code, we are loading the image and then resizing it to required dimensions. We haved added two Image resources. The Placeholder is the image shown to the user while the image is downloaded from the network. You can observe this in our demo video, while downloading, we can see the placeholder image momentarily.

    The Error image is shown to the user, if there was some error while loading the image. You can check this by providing an invalid URL for the image.

  5. Now in the MainActivity.java, add the following code:

    MainActivity.java

    Java
    package com.androidtutorialpoint.picassoandroidtutorial;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.AdapterView;
    import android.widget.GridView;
    import android.widget.ImageView;
    
    public class MainActivity extends AppCompatActivity {
        private GridView gridView;
        private Movie[] movies = {
                new Movie("Pulp Fiction",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/pulpfiction.jpg"),
                new Movie("Interstellar",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/interstellar.jpg"),
                new Movie("Batman v/s Superman",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/batmanvssuperman.jpg"),
                new Movie("Iron Man",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/ironman.jpg"),
                new Movie("Inception",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/inception.jpg"),
                new Movie("Avengers",
                "http://www.androidtutorialpoint.com/wp-content/uploads/2016/10/avengers.jpg"),
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            gridView = (GridView)findViewById(R.id.gridview);
            final MovieAdapter movieAdapter = new MovieAdapter(this, movies);
            gridView.setAdapter(movieAdapter);
    
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, 
                android.view.View view, int position, long id) {
                    Movie movie = movies[position];
                    movie.toggleFavorite();
    
                    // This tells the GridView to redraw itself
                    // in turn calling your MovieAdapter's getView method again for each cell
                    movieAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    In the MainActivity.java, we have created one movies array that has Movie name and URL to download the Movie Poster. We reference the GridView and add, then set instantiate and set the MovieAdaptor using the setAdaptor() method.

    If the user clicks on the Movie Poster, we toggle the Favorite in the setOnItemClickListener() for the Movie.

    That’s all folks, run your app in the emulator or an actual device. It will download the images, into grid view, now you can add the movies in your favorite list.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Hello Developer!

As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I hope you get the best possible value at of our platform. Stick with us for a while, and we promise you will become an $$Android Rockstar$$!

Android Tutorial Point is the right platform if you want to learn about android development. We have a broad collection of tutorials on different aspects of Android Development and it is growing rapidly. Here at Android Tutorial Point we thrive to deliver the best tutorials. In this direction, we are trying to create a community that will cater to your needs, whether you are a beginner or a seasoned veteran. For the beginners that are getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how to start with Android programming.


All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for latest android tutorials. You can reach out to us at our Facebook page https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at androidtutorialspoint@gmail.com

Comments and Discussions

 
-- There are no messages in this forum --