15

I just tried to use glide recyclerview integration and read a document about it and it said: "The RecyclerView integration library makes the RecyclerViewPreloader available in your application. RecyclerViewPreloader can automatically load images just ahead of where a user is scrolling in a RecyclerView", but I don't realise any difference between glide recyclerview integration and only glide, please explain what are advances of glide recyclerview integration? And how can I see the difference?

Here's my code:

GlideModule.kt

@GlideModule
class GlideModule : AppGlideModule() {
    override fun applyOptions(context: Context?, builder: GlideBuilder?) {
        val requestOp = RequestOptions.noAnimation()
                .priority(Priority.LOW)
        builder?.setDefaultRequestOptions(requestOp)
                ?.setLogLevel(Log.VERBOSE)
        super.applyOptions(context, builder)
    }

    // Disable manifest parsing to avoid adding similar modules twice.
    override fun isManifestParsingEnabled(): Boolean {
        return false
    }
}

MyPreloadModelProvide.kt

class MyPreloadModelProvide(val listUrls: List<String>, val context: Context) : PreloadModelProvider<Any> {
    override fun getPreloadItems(position: Int): MutableList<Any> {
        val url = listUrls.get(position)
        if (TextUtils.isEmpty(url)) {
            return Collections.emptyList();
        }
        return Collections.singletonList(url);
    }

    override fun getPreloadRequestBuilder(url: Any?): RequestBuilder<*>? {
        return GlideApp.with(context)
                .load(url)
    }

}

MyAdapter.kt

class MyAdapter(val listUrl: List<String>, val context: Context) : RecyclerView.Adapter<MyViewHolder>() {
    override fun getItemCount(): Int = listUrl.size

    @SuppressLint("CheckResult")
    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {

        GlideApp.with(context)
                .load(listUrl[position])
                .into(holder?.imageView)

        holder?.imageView?.setOnClickListener { Toast.makeText(context, listUrl[position], Toast.LENGTH_LONG).show() }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder = MyViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item, parent, false))
}

class MyViewHolder(view: View?) : RecyclerView.ViewHolder(view) {
    var imageView: ImageView

    init {
        imageView = view!!.findViewById(R.id.img)
    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var preloadSizeProvider: ViewPreloadSizeProvider<Any>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // glide
        var listUrls = listOf(
                "https://img.pokemondb.net/artwork/bulbasaur.jpg",
                "https://img.pokemondb.net/artwork/ivysaur.jpg",
                "https://img.pokemondb.net/artwork/komala.jpg",
                "https://img.pokemondb.net/artwork/turtonator.jpg",
                "https://img.pokemondb.net/artwork/togedemaru.jpg",
                "https://img.pokemondb.net/artwork/mimikyu.jpg",
                "https://img.pokemondb.net/artwork/nihilego.jpg",
                "https://img.pokemondb.net/artwork/buzzwole.jpg",
                "https://img.pokemondb.net/artwork/pheromosa.jpg",
                "https://img.pokemondb.net/artwork/xurkitree.jpg",
                "https://img.pokemondb.net/artwork/celesteela.jpg",
                "https://img.pokemondb.net/artwork/kartana.jpg",
                "https://img.pokemondb.net/artwork/guzzlord.jpg",
                "https://img.pokemondb.net/artwork/necrozma.jpg",
                "https://img.pokemondb.net/artwork/magearna.jpg",
                "https://img.pokemondb.net/artwork/marshadow.jpg"
        )

        preloadSizeProvider = ViewPreloadSizeProvider<Any>()
        val modelProvider = MyPreloadModelProvide(listUrls, this)
        val preloader = RecyclerViewPreloader(GlideApp.with(this), modelProvider, preloadSizeProvider, 2 /*maxPreload*/)

        // recycler view
        recycler_view.layoutManager = LinearLayoutManager(this)
        recycler_view.setHasFixedSize(true)
        recycler_view.adapter = MyAdapter(listUrls, this)

        // THERE ARE NO DIFFERENCES IF I COMMENT THIS LINE
        recycler_view.addOnScrollListener(preloader)
    }
}

THERE ARE NO DIFFERENCES IF I COMMENT THIS LINE recycler_view.addOnScrollListener(preloader)

donfuxx
  • 11,277
  • 6
  • 44
  • 76
vuhung3990
  • 6,353
  • 1
  • 45
  • 44

4 Answers4

3

The RecyclerView integration library makes the RecyclerViewPreloader available in your application.
And RecyclerViewPreloader can automatically load images just ahead of where a user is scrolling in a RecyclerView.

Combined with the right image size and an effective disk cache strategy, this library can dramatically decrease the number of loading tiles/indicators users see when scrolling through lists of images by ensuring that the images the user is about to reach are already in memory.

To use the RecyclerView integration library, add a dependency on it in your build.gradle file:

compile ("com.github.bumptech.glide:recyclerview-integration:4.4.0") {
  /*Excludes the support library 
    because it's already included by Glide.*/
  transitive = false
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99
chandrakant sharma
  • 1,334
  • 9
  • 15
3

The issue in your code is that you create preloadSizeProvider of type ViewPreloadSizeProvider, but you never call preloadSizeProvider.setView(...) on it. So it doesn't know the size of your target view, so it can't preload images in correct size, so you see no improvement.

I recommend first trying to make it work with fixed size. So instead of using ViewPreloadSizeProvider create FixedPreloadSizeProvider(WIDTH, HEIGHT) and make sure to use same size when loading images via Glide as such Glide.with(this).load(imageUri).override(WIDTH, HEIGHT).into(imageView);

If you want to check if it works, enable logging for both Glide requests like this (I used Java code there for my simplicity):

MyPreloadModelProvide.kt

class MyPreloadModelProvide(val listUrls: List<String>, val context: Context) : PreloadModelProvider<Any> {

    override fun getPreloadRequestBuilder(url: Any?): RequestBuilder<*>? {
        return GlideApp.with(context)
                .override(250, 250)
                .dontTransform()
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        Log.d("IMAGE PRELOAD", "onResourceReady() called with: model = [" + model + "], target = [" + target + "], dataSource = [" + dataSource + "]");
                        return false;
                    }
                })
                .load(url)
    }

}

MyAdapter.kt

class MyAdapter(val listUrl: List<String>, val context: Context) : RecyclerView.Adapter<MyViewHolder>() {
    override fun getItemCount(): Int = listUrl.size

    @SuppressLint("CheckResult")
    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {

        GlideApp.with(context)
                .load(listUrl[position])
                .override(250, 250)
                .dontTransform()
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        Log.d("IMAGE LOAD", "onResourceReady() called with: model = [" + model + "], target = [" + target + "], dataSource = [" + dataSource + "]");
                        return false;
                    }
                })
                .into(holder?.imageView)

        holder?.imageView?.setOnClickListener { Toast.makeText(context, listUrl[position], Toast.LENGTH_LONG).show() }
    }
}

And in logcat you should see that PRELOAD requests have dataSource = [LOCAL] or [RESOURCE_DISK_CACHE] and LOAD requests have dataSource = [MEMORY_CACHE].

It if works, great. Then you can rewrite it to use ViewPreloadSizeProvider. In that case you remove the fixed image size (.override(250,250)) from Glide requests and then don't forget to call preloadSizeProvider.setView(holder.imageView) for example in onCreateViewHolder method.

Robyer
  • 4,632
  • 2
  • 23
  • 21
1

Suppose the user is scrolling a RecyclerView that loads large images, so, the user should wait the delay of loading the image before seeing it in the corresponding list item. RecyclerViewPreloader loads the images in advance, so when the user scrolls, there are already loaded and ere displayed instantly.

In your code you are using a small list, and a small maxPreload value, so you won't notice the difference of using RecyclerViewPreloader. To see it in action you should use a long list with many different images, and scroll fast with and without the preloader. Without the preloader you will see empty images until loaded, and with it, images should be displayed rapidly and smoothly.

Raymond Arteaga
  • 4,355
  • 19
  • 35
1

My previous answer to this question was deleted, probably as from a quick glance of a moderator, it looks like it was totally unrelated, so I'll try and rephrase and add some meat.

Glide has a RecyclerView integration page that you might assume is the required way to get Glide working with an Android RecycerView. But it really just adds a memory cache preloader, which is a bit complicated to implement; the simple way of just adding Glide.with(view.context).load(url) into your RecyclerView onBindViewHolder works just as well and won't result in any memory leaks. And by default, Glide has a built in disk cache which works great.

So OP's question is what are the advantages of this memory preloader. The stated advantages are obvious, preloading images before the user scrolls to them.

But a better question is are the advantages worth the extra effort to get it working. This is a subjective question. It's only noticeable for users with slow Internet connections, and even then, I'm not sure it's worth the hassle. You've no idea where the user will scroll, you could preload images and then the user will scroll to the very bottom and images will need to be loaded new anyway. So IMO, it's not worth the hassle. But you'll have to make up your own mind.

georgiecasey
  • 21,793
  • 11
  • 65
  • 74