Posted on Leave a comment

Load image from URL, AsyncTask

Actually, the loading images from URL to ImageView (ImageView itself is in GridView or ListView) is not a simple task. You should provide memory and disk caching to avoid reload image again and again.

The simplest way is use library:

  1. Picasso (picasso-2.3.4.jar)
  2. Android universal image loader (grown from LazyList)
  3. Volley
  4. Glide
  5. Query

There is a comparison of these libraries (pdf 1, 2). Also this.

Also good article by Google’s ingineer (pdf)


How to use Picasso in Android Studio:
you should edit your build.gradle file by adding

[code language=”java”]
compile ‘com.squareup.picasso:picasso:2.3.4’
[/code]

My file looks like below

[code language=”java”]
apply plugin: ‘com.android.application’

android {
compileSdkVersion 19
buildToolsVersion "20.0.0"

defaultConfig {
applicationId "com.arvifox.testpica"
minSdkVersion 16
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
}
}
}

dependencies {
compile fileTree(include: [‘*.jar’], dir: ‘libs’)
compile ‘com.squareup.picasso:picasso:2.3.4’
}
[/code]

How to save image on disk by Picasso:

[code language=”java”]
public class MainActivity extends Activity{
ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image);
Picasso.with(this).load("your_url").error(R.drawable.error_detail)
.placeholder(R.drawable.ic_launcher)
.into(imageView, new EmptyCallback() {
@Override public void onSuccess() {
//to-do
}
@Override
public void onError() {
//to-do
}
});
Picasso.with(this).load("your_url")
.into(target);
}

private Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory().getPath() +"/path.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
};
}
[/code]

In the first part of code I put image to ImageView by just a few lines of code.

In second part I save image on disk by Target class that is described in Picasso library.

Note: Picasso uses the http headers to cache the image so it may not be stored for long. After sometime, it tries to load the image again from server instead of the cache. As a workaround, use “OkHttp” library made by the same people as Picasso. Just download its jar from here and put into your project’s libs directory. Picasso will use it by default and cache will be stored longer.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.