How to display image from URL in Android

The easiest way to display the image loaded from an URL is to use a package such as Picasso and Glide.

Moreover, some packages include useful features, for example, to load from cache, to set a placeholder image, and so on.

Introduction

There are two famous packages. They are Piccaso, which is simple, and Glide, which has a lot of functions.

Picasso

Picasso.get()
    .load(url)
    .into(imageView);

You can display an image with this simple code.

Glide v3

Glide.with(fragment)
    .load(url)
    .into(imageView);

You may use not only fragment but also context . Usage of Glide v3 is similar to that of Picasso.

Glide v4

GlideApp.with(fragment)
   .load(url)
   .error(new ColorDrawable(Color.BLACK))
   .into(imageView);

Generate some codes to use annotation processor in Java, so you don’t need to write complex settings

In Glide v4, you can use some methods to add configurations. For instance, .placeholder() is to set a placeholder image and .error() is to set an alternative image when an error happens. If you want to crop image roundly, .circleCrop() is helpful.

How To

In this time, I used Glide v4.

Gradle Settings

repositories {
  mavenCentral()
  maven { url 'https://maven.google.com' }
}

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
}

Manifest Settings

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name"

    <uses-permission android:name="android.permission.INTERNET"/>
    <!--
    Allows Glide to monitor connectivity status and restart failed requests if users go from a
    a disconnected to a connected network state.
    -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application>
      ...
    </application>
</manifest>

Add to the configuration of permission to connect the Internet because of getting images from an URL.

Proguard Settings

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

If you need, edit Proguard file.

New Java file

package com.example.myapp;

import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;

@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}

After you finish editing these setting and creating new Java file, execute [build] > [Rebuild Project]. In this step, you can call GlideApp object.