Main navigation

Android Picasso Tutorial Using Picasso Android Library

adsense

You might be thinking, why use another library since we have already disccussed about Android Volley and Android Retrofit 2.0 .

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.
  2. 	        Picasso.with(mContext)
                    .load(movie.getImageUrl())
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_error)
                    .into(imageView);
    
  3. No need to create a singleton for image downloading purpose as required for Android Volley
  4. Automatic Handling of Memory and disk caching logic as well.
  5. Support for image post processing like resizing and rotation of the downloaded image using simple commands.
  6. Support for Request cancellation and parallel downloading.

In this Android Picasso Tutorial, we will create an app that will Picasso Android Library to 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 for 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.
  2. build.gradle

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

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

Adding Functionality

  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.
  2. Movie.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;
        }
    }
    
  3. Next add aGridView to your activity_main.xml to show the images
  4. activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:tools="https://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>
    
  5. 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.
  6. movie_layout.xml

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:tools="https://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.
  7. o 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.
  8. MovieAdaptor.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.

  9. Now in the MainActivity.java, Add the following code.

    MainActivity.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","https://www.androidtutorialpoint.com/wp-content/uploads/2016/10/pulpfiction.jpg"),
                new Movie("Interstellar","https://www.androidtutorialpoint.com/wp-content/uploads/2016/10/interstellar.jpg"),
                new Movie("Batman v/s Superman","https://www.androidtutorialpoint.com/wp-content/uploads/2016/10/batmanvssuperman.jpg"),
                new Movie("Iron Man","https://www.androidtutorialpoint.com/wp-content/uploads/2016/10/ironman.jpg"),
                new Movie("Inception","https://www.androidtutorialpoint.com/wp-content/uploads/2016/10/inception.jpg"),
                new Movie("Avengers","https://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.




    What’s Next ??

    You can create beautiful image gallery apps using Picasso Android Library.
    We hope you liked our Android Picasso Example, please leave comments in the comment section below in the case of any doubts.

    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    To download the full code for the Android Picasso Tutorial app, Click on the Download Now link below.

    Android Picasso Tutorial Download Now


Reader Interactions

Leave a Reply

Advertisment ad adsense adlogger