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.
- To download an Image, all you need to write is these five magical lines.
Picasso.with(mContext)
.load(movie.getImageUrl())
.placeholder(R.drawable.ic_placeholder)
.error(R.drawable.ic_error)
.into(imageView);
- No need to create a singleton for image downloading purpose as required for Android Volley
- Automatic Handling of Memory and disk caching logic as well
- Support for image post processing like resizing and rotation of the downloaded image using simple commands
- 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
- Go to File → New → New Project and enter your Application Name.
- 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.
- 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.
- 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:
- Now open your project’s
build.gradle
from the project’s home directory and add the following dependency.
build.gradle
compile 'com.squareup.picasso:picasso:2.5.2'
- Since we need to connect to the network add the Internet permission in AndroidManifest.xml file.
<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
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())
.placeholder
(R.drawable.ic_placeholder)
.error(R.drawable.ic_error)
.resize(300, 500)
.into(imageView);
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.
- 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
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;
}
}
- Next add a
GridView
to your activity_main.xml to show the images:
activity_main.xml
="1.0"="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>
- 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
<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:
- An
ImageView
for the Movie Poster - An
ImageView
for a favourite icon - A
TextView
for the Movie name
- 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
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())
.placeholder
(R.drawable.ic_placeholder)
.error(R.drawable.ic_error)
.resize(300, 500)
.into(imageView);
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.
- 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",
"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();
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.