How to load image from URL

Programming Tutorial
To access an image from a URL and then load it in ImageView in android we usually go by using an AsyncTask but there is a library called Picasso that can help us a lot in making the process much much easier.


Here is the link to Download Picasso:

Here is the link to the official web page:

http://square.github.io/picasso/


Adding picasso to Android Studio:
simply go to your buld.gradle file in your project and
add this compile script at the end and gradle sync
 Viola! 


Watch this Video to learn How, Easily....

Once you've added the library to your package:
A single statement can do the job for you, that being:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
where  "http://i.imgur.com/DvpvklR.png" must be replaced by your image URL.
imageView must be replaced with your imageView object.

for example :
ImageView iv=(ImageView)findViewById(R.id.my_image_id_in_xml); 
Picasso.with(MainActivity.this).load("http://square.github.io/picasso/static/debug.png").into(iv);

What happens if it is unable to load the image?
Well, there may be many situations when the app fails to load the image like when there is no internet, then you can use the place holder function in picasso to replace the imageview with a locally available image. It will make three attempts to load the image before it uses the placeholder.
eg: you could have an image with a cross mark on it telling the user about the problem
Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)
    .error(R.drawable.user_placeholder_error)
    .into(imageView);
R.drawable.user_placeholder will be the substitute image


Can you use system files as image sources rather than a URL? yes!
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
Resize and Scale the image before you load:
Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView




Comments

Popular posts from this blog

How to add a library to Android Studio

How to add new theme in Android studio