Skip to main content

Picasso Android Example


In this post I am about to show you, how to cache an image and display it in Android application, you can also use Picasa to save the Image that you are caching to local directory. 

You can download the library .jar file from here.

key Features of Picasso Library Android:

Easy to code with Picasso --> With single line of code you can able to cache Image to your application or download Image to local directory of your phone. 

Handles ImageView Recycling in Adapter -->  Let's take an listview adapter for example, if you are about to use Picasso to display images to a listview , the caching and cancellation of caching when the list child is visible or Invisible is handled automatically by Picasso. 

PlaceHolder --> You can use place holder to notify the user, what's happening when the image caching starts, so before displaying the complete image on the view, you can display an image prior to that notifying the user what's happening like (download Has started).

Error PlaceHolder --> Here you can display an image to the view, when there is an error caching image to the android application. 

Only setBack that I found in Picasso is, you can't cache Gif type image with Picasso, if you really need to cache a Gif image use Glide instead.

Download the complete Android Studio Project From here.



1.MainActivity.java:



final com.squareup.picasso.Target saveImageToDirectory = new com.squareup.picasso.Target() {  
       @Override  
       public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {  
         ProgressDialog mydialog = new ProgressDialog(MainActivity.this);  
         mydialog.setMessage("saving Image to phone");  
         mydialog.show();  
         try {  
           file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"bird.jpeg");  
           //new File(path for the file to be saved, saving file name)  
           if (!file.exists()) {  
             //check if the file already exist or if not create a new file  
             //if exist the file will be overrighted with the new image  
             file.createNewFile();  
           }  
           FileOutputStream ostream = new FileOutputStream(file);  
           bitmap.compress(Bitmap.CompressFormat.JPEG, 70, ostream);  
           //Normal file creation process.  
           //With Image needed type.  
           Toast.makeText(MainActivity.this, "File Saved here" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();  
           ostream.close();  
           mydialog.dismiss();  
         } catch (Exception e) {  
           mydialog.dismiss();  
           Log.e("file creation error", e.toString());  
         }  
       }  
       @Override  
       public void onBitmapFailed(Drawable errorDrawable) {  
       }  
       @Override  
       public void onPrepareLoad(Drawable placeHolderDrawable) {  
       }  
     };  
     cacheAndDisplayImage.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Picasso.with(MainActivity.this).load("http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg").placeholder(R.drawable.downloading).error(R.drawable.error).into(displayImageHere);  
         //cache and display the image to ImageView placeHolder(image) an image which show information to the user showing it's downloading.  
         //.error(image) display the default image on the image if there is an cache error(like Cache Image failed due to network error)  
       }  
     });  
     cachewithWidthAndHeight.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Picasso.with(MainActivity.this).load("http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg").placeholder(R.drawable.downloading).error(R.drawable.error).resize(500, 500).centerCrop().into(displayImageHere);  
         //Cache and Display Image with Programmer defined Width and Height.   
       }  
     });  
     handleDownloadFailure.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Picasso.with(MainActivity.this).load("hello").placeholder(R.drawable.downloading).placeholder(R.drawable.downloading).error(R.drawable.error).into(displayImageHere);  
         //code to explain download failure, error handler will display an image, when download error occurs.   
       }  
     });  
     saveImageToPhone.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Picasso.with(MainActivity.this).load("http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg").placeholder(R.drawable.downloading).error(R.drawable.error).into(saveImageToDirectory);  
         //Save Image to phone with PlaceHolder and On error placeholder handler.   
       }  
     });  
     loadImageToAdapter.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v)  
       {  
         //creates a new Activity and display the Image in Adapter to explain automatic handling of Image Download and Cancellation.   
         Intent intent=new Intent();  
         intent.setClass(MainActivity.this,GridviewForAdapter.class);  
         startActivity(intent);  
       }  
     });  
   }  
 }  

The above code contain commented lines with explanation for each line of code.

2.Activity_main.xml:


 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   android:orientation="vertical"  
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">  
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/cacheAndDisplayImage"  
     android:text="Cache and Display Image As It is"  
     />  
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/cachewithWidthandHeight"  
     android:text="Display with custom Width and Height"  
     />  
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/LoadDefaultImageOnFailure"  
     android:text="Load Default Image when Failed to Download"  
     />  
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/saveImageToPhone"  
     android:text="Save Image to phone"  
     />  
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/loadImagesToAdapter"  
     android:text="Load Image to Adapter"  
     />  
   <ImageView  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:id="@+id/displayImageHere"  
     />  
   </LinearLayout>  

3.AdapterToLoadImageInGridvew.java



public class AdapterToLoadImageInGridview extends BaseAdapter {  
   private String[] imagePathArray;  
   private Context tcontext;  
   private LayoutInflater inflater;  
   public ViewHolder holder;  
   public AdapterToLoadImageInGridview(Context context,String imagePathArray[]) {  
     this.imagePathArray=imagePathArray;  
     this.tcontext=context;  
     this.inflater=LayoutInflater.from(context);  
   }  
   @Override  
   public int getCount() {  
     return imagePathArray.length;  
   }  
   @Override  
   public Object getItem(int position) {  
     return null;  
   }  
   @Override  
   public long getItemId(int position) {  
     return 0;  
   }  
   @Override  
   public View getView(int position, View convertView, ViewGroup parent) {  
     if (convertView == null) {  
       convertView=inflater.inflate(R.layout.layoutforimageview,null);  
       holder=new ViewHolder();  
       holder.imageView=(ImageView)convertView.findViewById(R.id.imageViewForAdapter);  
       convertView.setTag(holder);  
     }  
     else {  
       holder=(ViewHolder)convertView.getTag();  
     }  
     Picasso.with(tcontext).load(imagePathArray[position]).placeholder(R.drawable.downloading).error(R.drawable.error).into(holder.imageView);  
     return convertView;  
   }  
   static class ViewHolder {  
     ImageView imageView;  
   }  
   }  


4.GridViewForAdapter.java(Second Activity Java File)


public class GridviewForAdapter extends AppCompatActivity {  
   GridView gridview;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.gridviewforadapter);  
     gridview=(GridView) findViewById(R.id.gridView);  
     String[] imagePath={"http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg","http://www.freestockphotos.name/wallpaper-original/wallpapers/download-images-of-gentle-dogs-6866.jpg","http://www.travel-tw.com.tw/img/p3.jpg","http://i1008.photobucket.com/albums/af201/visuallightbox/Butterfly/13.jpg","http://www.thinkstockphotos.in/CMS/StaticContent/Hero/TS_AnonHP_462882495_01.jpg","http://www.quicksprout.com/images/foggygoldengatebridge.jpg","http://www.gettyimages.in/gi-resources/images/CreativeImages/Hero-534897989.jpg"};  
     AdapterToLoadImageInGridview adapterToLoadImageInGridview=new AdapterToLoadImageInGridview(GridviewForAdapter.this,imagePath);  
     gridview.setAdapter(adapterToLoadImageInGridview);  
   }  
 }  


5.Gradle Dependencies:

  compile 'com.squareup.picasso:picasso:2.5.2'  

That's it. Hope it helps. 

Comments

Post a Comment

Popular posts from this blog

Hiding a Child item(ImageView) In ListView

Download Complete Android Studio Project by  Clicking Here . Important Things About Listview: i.                A List view Recycle it’s view. Meaning If your screen can only fit 5 items. But the total number of item   you are about to display in listview is 100 . ii.               Android won’t load these 100 items into the listview when you set your adapter. iii.             Instead it first load the first five Items on the screen and when you scroll down , it fills the new data into the listview, Which improves performance and Memory. ListView at First Load Item 1   Item 2 Item 3 Item 4 Item 5 ListView When Scrolled Item 3   Item 4 Item 5 Item 6 Item 7 Let’s say you scroll down to view Two more elements item 6 and 7. What happens here is the last two row will be updated with the new value   item 6 and item 7..i.e handled by the adapter

Adding Json array to Serializable Class using Gson.

Why you should use Gson and Serializable Class to Handle Json Data: Gson can be used along with Serializable class to save variables, unnecessary loops and memory  to save the data you get from Json.  Let's Imagine you have array of contact detail and its total count is four. which is something like this. Json Snippet: [ { "name" : "Mark" , "phoneNumber" : "1008788666" , "emailId" : "mark@mail.com" , "address" : "600 Pennsylvania Avenue, Washington DC" }, { "name" : "Christian" , "phoneNumber" : "8007780066" , "emailId" : "christian@mail.com" , "address" : "11 Wall Street New York" }, { "name" : "Benedict" , "phoneNumber" : "4258781555" , "emailId" : "ben

Sugar ORM With Sqlite Android Part I

Sugar ORM  Android Part I:              If you have came this far in search of how to use an ORM database with your application , you are very much familiar with pain that SQLite querying concept is giving you for all basic CRUD operations with the database. Sugar ORM is  one of the solution which is available for you to carry out CRUD operation in ease, There is no need to use cursor  for reading from database, Sugar ORM speaks Object with Sqlite database. Sugar ORM consider a row of data as Object, where SQLite consider it as record. In this example I am going to show you how to create a table and add data to it using Sugar ORM. Let's get started. 1. Library Inclusion First and Foremost thing, add Sugar ORM to your project by adding the following line to your app dependencies. compile 'com.github.satyan:sugar:1.4' 2. Add Database configuration to Application Manifest: We have to inform the android sdk, that we are using SugarORM to handle CRUD