Android Glide Example

Glide is a famous image loading and management open source library contributed by Bump Technologies. It can be used to load any format image ( gif, png, jeg etc ). It is often used  in android application. It is fast and easy to use. This article will tell you how to use it.

1. Android Sdk Requirements.

To use glide library, you should have minimum sdk version bigger than 14. And the compile sdk version must be 27 or higher. And the support library version should also be 27. If you meet any errors when update your android studio sdk version to 27, you can read following two articles.

  1. How To Resolve Errors When Change SDK Level In Android Studio
  2. How To Resolve Android Studio SDK Platform-Tools Version Is Too Old Error

2. Add Dependency In Android Project.

After upgrade android studio sdk, you need to add below dependencies in our project build.gradle file dependencies section.

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support:design:27.1.0'
    compile 'com.github.bumptech.glide:glide:4.6.1'

    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}

Because this example will load image from internet through image url, so we should add below permission in AndroidManifest.xml file also.

<uses-permission android:name=”android.permission.INTERNET” />

3.Use Glide To Load Image Example.

Use glide you can load images from multiple resources follow below steps.

  1. From internet use image url.// Create glide request manager
    RequestManager requestManager = Glide.with(this);
    // Create request builder and load image.
    RequestBuilder requestBuilder = requestManager.load(imageUrl);
    
    // Show image into target imageview.
    requestBuilder.into(imageView);
  2. From local file system.
    RequestManager requestManager = Glide.with(this);
    
    File imageFile = new File(getExternalCacheDir() + "/image.jpg");
    
    RequestBuilder requestBuilder = requestManager.load(imageFile );
    
    requestBuilder.into(imageView);
  3. From image Uri object return by other content provider.
    RequestManager requestManager = Glide.with(this);
    
    Uri imageUri = getImageUri();
    
    RequestBuilder requestBuilder = requestManager.load(imageUri );
    
    requestBuilder.into(imageView);
  4. From drawable resource.
    RequestManager requestManager = Glide.with(this);
    
    RequestBuilder requestBuilder = requestManager.load( R.drawable.img1 );
    
    requestBuilder.into(imageView);
  5. From binary stream.
    RequestManager requestManager = Glide.with(this);
    
    byte[] imageByte = getImageByteArr();
    
    RequestBuilder requestBuilder = requestManager.load( imageByte );
    
    requestBuilder.into(imageView);
    

4. Example Overview.

There are three button in this example. When you click the first button, it will load a gif image from internet and display it in image view as below.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/l0y_sRenQsM

When you click the second button, it will display a loading image placeholder before regular target image load complete. If there are something wrong such as network connection error occurred during the load process, it will display the error placeholder image.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ZnRkFrEuUzw

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/MAluzDv7I4I

When you click the third button, it will change the loaded image size displayed in the imageview.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/-KfE00Ap34w

5. Main Activity.

GlideBasicActivity.java

package com.dev2qa.example.image.glide;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.dev2qa.example.R;

public class GlideBasicActivity extends AppCompatActivity {

    private Button loadImageButton = null;

    private Button loadImageWithPlaceholderButton = null;

    private Button loadImageSpecialSizeButton = null;

    // Used to show glide load image.
    private ImageView imageView = null;

    private RequestManager requestManager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_glide_basic);

        setTitle("dev2qa.com - Android Glide Example");

        initControls();

        loadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String imageUrl = "http://barkpost.com.br/wp-content/uploads/2017/01/ezgif.com-1f95816829.gif";
                loadImageWithGlide(imageUrl);
            }
        });

        loadImageWithPlaceholderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String imageUrl = "http://wallpapers.ae/wp-content/uploads/2015/09/Maldives-sea-wallpaper.jpg";
                int imagePlaceHolder = R.drawable.load_image_placeholder;
                int errorPlaceHolder = R.drawable.load_image_error_placeholder;
                loadImageWithGlideImagePlaceholder(imageUrl, imagePlaceHolder, errorPlaceHolder);
            }
        });

        loadImageSpecialSizeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String imageUrl = "http://wallpapers.ae/wp-content/uploads/2015/09/Maldives-sea-wallpaper.jpg";
                loadImageWithGlideSpecialSize(imageUrl, 500, 500);
            }
        });

    }


    /* Initialize ui controls.*/
    private void initControls()
    {
        if(loadImageButton == null)
        {
            loadImageButton = (Button)findViewById(R.id.glide_load_image_button);
        }

        if(loadImageWithPlaceholderButton == null)
        {
            loadImageWithPlaceholderButton = (Button)findViewById(R.id.glide_load_image_placeholder_button);
        }

        if(loadImageSpecialSizeButton == null)
        {
            loadImageSpecialSizeButton = (Button)findViewById(R.id.glide_load_image_special_size_button);
        }

        if(imageView == null)
        {
            imageView = (ImageView)findViewById(R.id.glide_load_image_image_view);
        }

        if(requestManager == null)
        {
            // Create a glide request manager.
            requestManager = Glide.with(this);
        }
    }


    private void loadImageWithGlide(String imageUrl)
    {
         // Create glide request builder.
         RequestBuilder requestBuilder = requestManager.load(imageUrl);

         // Create glide request option.
         RequestOptions requestOptions = new RequestOptions();

         // Apply glide request options.
         requestBuilder.apply(requestOptions);

         // Load image to image view to display.
         requestBuilder.into(imageView);
    }

    /* Show image loading placeholder before load complete. */
    private void loadImageWithGlideImagePlaceholder(String imageUrl, int imagePlaceHolder, int errorPlaceHolder)
    {
        RequestBuilder requestBuilder = requestManager.load(imageUrl);

        RequestOptions requestOptions = new RequestOptions();
        
        // Set place holder image resource id.
        requestOptions.placeholder(imagePlaceHolder);

        /* Set load image error place holder resource id. When image can not be loaded show this image.*/
        requestOptions.error(errorPlaceHolder);

        // Do not use glide cache to store loaded image.
        requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);

        requestBuilder.apply(requestOptions);

        requestBuilder.into(imageView);
    }

    /* Load image and change the image size.*/
    private void loadImageWithGlideSpecialSize(String imageUrl, int width, int height)
    {
        RequestBuilder requestBuilder = requestManager.load(imageUrl);

        RequestOptions requestOptions = new RequestOptions();

        // Specify image size.
        requestOptions.override(width, height);

        requestBuilder.apply(requestOptions);

        requestBuilder.into(imageView);
    }
}

6. Activity Layout Xml File.

activity_glide_basic.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/glide_load_image_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Image With Url"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/glide_load_image_placeholder_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Image With Image Placeholder"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/glide_load_image_special_size_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Image Specify Image Size"
        android:textAllCaps="false"/>

    <ImageView
        android:id="@+id/glide_load_image_image_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

7. Android Manifest Xml File.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity android:name=".image.glide.GlideBasicActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Leave a Comment

Your email address will not be published. Required fields are marked *

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