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.
The above code contain commented lines with explanation for each line of code.
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.
Thanks it helps alot!!
ReplyDeleteThanks for sharing the information..... keep sharing more articles
ReplyDeleteWe provide best Selenium training in Bangalore, automation testing with live projects. Cucumber, Java Selenium and Selenium Training in Bangalore
Software Testing Training in Bangalore
Java Selenium Training in Bangalor
Best Selenium Training in Bangalore
Best Selenium Training Institute in Bangalore
https://bit.ly/3dlEu2i
ReplyDelete