A tutorial on using glide to load pictures in Android apps _android

Source: Internet
Author: User
Tags error handling locale object model

As with other picture loading libraries, glide can load local pictures in addition to the network pictures. You can even load pictures from a variety of exotic data sources.

Load Network picture
In many cases, we use the picture loading library to load the network picture. Network operation is a very complex thing. Imagine, if there is no picture loading library, we will manually download pictures, cache pictures, and finally from the file read bitmap and set into the ImageView inside. That's a good one, but you'll have more headaches in ListView. The reason I do not say, you know ~ ~ plus a variety of bitmap operations, you are sure you do not want to masturbate code. And bitmap This thing still very occupy memory, wait and wait for bad, very easy will trigger Oom,app to flash the back!!

This is the advantage of the picture loading library. Simple words, download, cache, load all buttoned up. It's just a beautiful life thing. And Glide is one of the things that makes a person a good life.

Say so much, glide how to load network picture? Very simple, the last three words:

ImageView Targetimageview = (imageview) Findviewbyid (R.id.imageview);
String InternetURL = "Http://i.imgur.com/idojSYm.png";
Glide. with
  [context]
  . Load (InternetURL)
  . into (Targetimageview);

What a mess of wood, directly passed to the URL to load the picture can be. Then there are a lot of picture loading library, why Choose Glide? Very simple, because it is smooth, not card, especially in the ListView. Yes, it's the sauce.

Load local picture
The following table shows the parameters and descriptions that can be passed in. Load ()

Parameters Description
. Load (String string) A string can be a file path, URI, or URL
. Load (URI uri) URI type
. load (file file) File
. Load (Integer ResourceID) Resource id,r.drawable.xxx or R.mipmap.xxx
. Load (byte[] model) Byte[] Type
. Load (T model) Custom type

From the above you can see that glide not only can load network pictures, but also can load local pictures. Acceptable parameters include file path, URI, file, resource ID, and so on. Basically meet most of the needs. Although loading local pictures is not as complex as network pictures, I recommend using glide to load local pictures. Because it is memory friendly, but also "secretly" to help us do a lot of things. For example, memory cache, bitmap multiplexing, fixed photo direction, and so on. Of course, in order to meet a variety of needs, just loading pictures is not enough, you also need to make a variety of images, that is, transformation. We'll learn more about that later.

Load a custom data source
one of the previous tables is that we are unfamiliar with. Load (T model), which is a custom data source type. So how to achieve it?

In fact, loading a custom data source is primarily accomplished through the Modelloader interface. There is less experience in this area, since it has not been used in actual projects.

But from the official wiki, the design of the Modelloader interface was designed to load different sizes of pictures. As we all know, Android device screen resolution is strange, large to 2K, small to 320p. If you load a large image on a low resolution mobile phone, not only the loss of user traffic, but also easy to cause oom; On the high resolution of the mobile phone, load small map will appear blurred situation, the user experience is very poor. Many times, for the sake of convenience, many apps will choose an intermediate resolution and then adapt to size. Of course this is understandable, but there is a better way, why don't we try?

So how do you use glide to achieve this specific requirement? First of all, you want to achieve your own modelloader, the simpler way is to inherit Baseglideurlloader.

Public interface Mydatamodel {public
  String buildurl (int width, int height);
} 
public class Myurlloader extends baseglideurlloader<mydatamodel> {
  @Override
  protected String getUrl ( Mydatamodel model, int width, int height) {
    //construct the URL for the correct size here.
    Return Model.buildurl (width, height);
  }

Next we can load the picture like this:

Glide.with (this)
   . using (The new Myurlloader (this))
   . Load (new Mydatamodel () {
     @Override public
     String Buidurl (int width, int height) {
       if (width >=) {return
         url1;
       } else {return
         url2;
     }}
   })
   . Into (ImageView);

(1). using (new Myurlloader (This)): Use our own modeloader;
(2). Load (new Mydatamodel ()): Load our custom data source

Here you need to explain the three parameters of the following geturl:
(1) Model: The data source you loaded
(2) Width: The breadth of the picture you load (px)
(3) Height: The altitude of the picture you Loaded (px)

In this way, we load the URL1 on a high rate device and load the small image url2 on a low-resolution device. So that the need to load different size pictures according to the pixel value of different mobile phones.

Of course, if you don't want to use the. using (New Myurlloader ()) each time, you need to implement a custom modelloaderfactory and register in Glidemodule.

public class Myglidemodule implements Glidemodule {
  ...
  @Override public
  void registercomponents (context context, Glide Glide) {
    glide.register (Mydatamodel.class, Inputstream.class, 
      new Myurlloader.factory ());
  }

And also in the Androidmanifest.xml statement

<meta-data
  android:name= "Com.mypackage.MyGlideModule"
  android:value= "Glidemodule"/>

If you have more than one custom Glidemodule class, then also declare multiple glidemodule in the Androidmanifest.xml.

There are several URLs that can be loaded on the service side:

URL Picture Size
myserver.com/images/__w-200-400-600-800-1000__/session1.jpg Original size
Myserver.com/images/w200/session1.jpg 200px
Myserver.com/images/w400/session1.jpg 400px
Myserver.com/images/w600/session1.jpg 600px
Myserver.com/images/w800/session1.jpg 800px
Myserver.com/images/w1000/session1.jpg 1000px

So how does the client load different URLs according to the different resolution of the mobile phone?

Google does this, and the following is the core code:

Define regular Expressions
private static final pattern =
   pattern.compile ("__w-(?:-?\\d+) +)");

@Override
protected String GetUrl (string model, int width, int height) {
  Matcher m = pattern.matcher (model);
  int bestbucket = 0;
  if (M.find ()) {
    string[] found = M.group (1). Split ("-");//Get the size array that can be loaded for
    (String bucketstr:found) {
      Bestbucket = Integer.parseint (BUCKETSTR);
        Requested width break
        ;
      }
    if (Bestbucket > 0) {//returns the appropriate size URL
      model = M.replacefirst ("w" +bestbucket);
    }
  return model;
}

The approximate steps are as follows:
1. Define regular expressions based on the server-side picture URLs that can be loaded
2. Obtain a picture size array that can be loaded based on a regular match
3. According to the size of the ImageView to be loaded, select the appropriate size URL
4. Splice URL and return

The above example has 200,400,600,800,1000 can be loaded, if you want to load the ImageView size of 600px, when traversing the array to 600, will jump directly out of the loop, return the 600px size of the image URL, Glide will load 600px of pictures.

Exception debugging
When an exception occurs during glide loading of a picture, the default is no log output. But glide provides developers with two ways to view or respond to these exceptions.
1. Debugging
In order to see them when they occur, you can open the log switch in glide that handles all media load responses in the class Genericrequest. Quite simply, run the following instructions at the command line:

adb shell SetProp log.tag.GenericRequest DEBUG

If you replace debug with verbose, you can also see a detailed request-time log.
If you want to disable log output, execute:

adb shell SetProp log.tag.GenericRequest ERROR

2. Debug Workflow

To see when and how to load a picture for the glide internal engine, you can enable these logs:

adb shell SetProp log.tag.Engine VERBOSE
adb shell setprop log.tag.EngineJob VERBOSE
adb shell SetProp log.tag.De Codejob VERBOSE

Enabling these logs can help you understand why some resources are not loaded from memory? Why load from an external URL to download data again? It also helps to understand which parameters need to be configured when the disk is cached. Enabling Decodejob log also helps you understand related issues such as custom transform/decoder/encoder.
3. Request Listener
Although it is easy to start the debug log, the prerequisite is that you can access the device. In order to improve glide existing or more complex error logging systems, you can use the Requestlistener class. When the load request fails, the Onexception () method is invoked, giving the exception that caused the failure or null (when the decoder is unable to decode any useful things from the data it obtains). You can add a listener to each request through the listener () API. The
ensures that the return value of the Onexception () method is false to avoid overwriting glide default error handling (such as the error picture placeholder for loading failures).
Here is a quick-debugging:

Example:. Listener (New logginglistener<string, glidedrawable> ()) Public 
class Logginglistener<t, r> Implements Requestlistener<t, r> {
  @Override public boolean onexception (Exception E, Object model, Target Targe T, Boolean Isfirstresource {
    android.util.log.d ("GLIDE", String.Format (Locale.root,
        "Onexception" (%s,%s,%s) ,%s) ", E, model, Target, Isfirstresource), e);
    return false; 
  } 
  @Override public boolean Onresourceready (object resource, object model, Target target, Boolean Isfrommemorycache, Boolean Isfirstresource) {
    android.util.log.d ("GLIDE", String.Format (Locale.root,
        "Onresourceready" (%s,%s,%s,%s,% s) ", resource, model, Target, Isfrommemorycache, isfirstresource);
    return false; 
  } 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.