Hot questions for Using Glide in mediastore


I have a recycler view within a fragment and basically I m trying to load song list in the recycler view .Each row of recycler view contains an imageview (for album art) and textview ( for song name). I am having trouble when the size of the dataset is huge, that is when there are too many songs, the recycler view lags and the app ends up giving an ANR.I am using Glide to load album arts in each row's imageview. How is google music player able to show such large number of songs without any lag?

Edit: This is my SongsFragment

public class SongsFragment extends Fragment {
static {
ProgressBar progressBar;    // progress bar to show after every 30 items
NestedScrollView nestedScrollView;  //for smooth scrolling of recyclerview as well as to detect the end of recyclerview
RecyclerView recyclerView;
ArrayList<Song> songMainList = new ArrayList<>();  //partial list in which items are added
ArrayList<Song> songAllList = new ArrayList<>(); //Complete List of songs
SongAdapter songsAdapter;
private LinearLayoutManager layoutManager;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_songs, container, false);

    nestedScrollView = (NestedScrollView) rootView.findViewById(;
    progressBar = (ProgressBar) rootView.findViewById(;

    String songJson = getActivity().getIntent().getStringExtra("songList");
    songAllList = new Gson().fromJson(songJson, new TypeToken<ArrayList<Song>>() {
            //Getting list of all songs in songAllList

    if (songAllList.size() > 30) {  
        songMainList = new ArrayList<>(songAllList.subList(0,30));
    } else {
        songMainList = songAllList;

    //if size of fetched songAllList>30 then add only 30 rows to songMainList

    recyclerView = (RecyclerView) rootView.findViewById(;
    int spanCount = 1; // 2 columns
    int spacing = 4; // 50px
    recyclerView.addItemDecoration(new GridItemDecoration(spanCount, spacing, true));
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    songsAdapter = new SongAdapter(getActivity(), songMainList, recyclerView);

    nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        public void onScrollChanged() {
            View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
            int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView

            if (diff == 0) {    //NestedScrollView scrolled to bottom
                progressBar.setVisibility(View.VISIBLE);    //show progressbar
                new Handler().postDelayed(new Runnable() { 
                    public void run() {
                        if (songMainList.size() < songAllList.size()) {
                            int x = 0, y = 0;
                            if ((songAllList.size() - songMainList.size()) >= 30) {
                                x = songMainList.size();
                                y = x + 30;
                            } else {
                                x = songMainList.size();
                                y = x + songAllList.size() - songMainList.size();
                            for (int i = x; i < y; i++) {
                                songMainList.add(songAllList.get(i));   //Adding new items from songAllList to songMainList one by one
                }, 1500);


    return rootView;

And this is my RecyclerViewAdapter along with viewholder

public class SongAdapter extends RecyclerView.Adapter {

private List<Song> songsList;
private Context c;

private RecyclerView.ViewHolder holder;

public SongAdapter(Context context) {
    mainActivityContext = context;

public SongAdapter(Context context, List<Song> songs, RecyclerView recyclerView) {
    songsList = songs;
    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    c = context;

public SongAdapter getInstance() {
    return SongAdapter.this;

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.song_list_row, parent, false);
    return new SongViewHolder(view,c);

public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof SongViewHolder) {
        Song song = songsList.get(position);
        this.holder = holder;

        String name = song.getName();
        String artist = song.getArtist();
        String imagepath = song.getImagepath();

        ((SongViewHolder) holder).name.setText(name);

        ((SongViewHolder) holder).artist.setText(artist);

        if (!imagepath.equalsIgnoreCase("no_image")) //if the album art has valid  imagepath for this song

                    .into(((SongViewHolder) holder).iv);
            ((SongViewHolder) holder).iv.setImageResource(R.drawable.empty);

        ((SongViewHolder) holder).song = song;

public int getItemCount() {
    return songsList.size();

static class SongViewHolder extends RecyclerView.ViewHolder{

    ImageView iv;
    TextView name, artist;
    CardView songListCard;
    private Context ctx;

    private OnLongPressListener mListener;

    SongViewHolder(View v, Context context) {
        this.ctx = context;
        iv= (ImageView) v.findViewById(;
        name= (TextView) v.findViewById(;
        artist= (TextView) v.findViewById(;
        songListCard = (CardView) v.findViewById(;

The recyclerview works fine when there are only 150-200 items but when reaching to 600-700 items , the whole app slows down. Could this be because of the way I have used glide in onBindViewHolder?


Sort answer:

LinearLayoutManager(context).apply { isAutoMeasureEnabled = false }
// or in Java

From the doc of RecyclerView.LayoutManager#setAutoMeasureEnabled() we know :

This method is usually called by the LayoutManager with value {@code true} if it wants to support WRAP_CONTENT

It works by calling {@link LayoutManager#onLayoutChildren(Recycler, State)} during an {@link RecyclerView#onMeasure(int, int)} call, then calculating desired dimensions based on children's positions.

If we set mAutoMeasure = true, it will call LayoutManager#onLayoutChildren(Recycler, State) during an RecyclerView#onMeasure(int, int) call. Every child view's onMeasure() method will be called, this cost too much time.

Let's look at LinearLayoutManager's constructor

public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {

So, after we set mAutoMeasure = false, everything will be ok.


Questions around Android Q and Glide have been asked before but I'm not able to put them all together, so I hope someone is willing to help.

I'm saving images, downloaded from the cloud(Firebase) or chosen from gallery or taken with the camera, to local storage. I used to save it in the app's folder and could add it to the gallery, but with Android Q that is not possible anymore. So I changed my app to use the MediaStore and ContentResolver to access files and save it. Files are saved in the Pictures directory of MediaStore.Images.Media.EXTERNAL_CONTENT_URI.


public Uri createUriForFile(String fileName, String parentId)
        Uri uriFromContentResolver = getUriFromContentResolver(fileName);
        if(uriFromContentResolver != null)
            return uriFromContentResolver;
            ContentResolver resolver = baseActivity.getApplicationContext().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, EXTERNAL_PICTURE_RELATIVE_PATH);
            return resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    }else {
        File pictureFile  = new File( EXTERNAL_PICTURE_STORAGE_DIR.getAbsolutePath() + File.separator + parentId + File.separator + fileName );
        return FileProvider.getUriForFile(baseActivity, baseActivity.getApplicationContext().getPackageName() + ".fileprovider", pictureFile);

public Uri getUriFromContentResolver(String fileName)
        ContentResolver resolver = baseActivity.getApplicationContext().getContentResolver();

        Cursor queryCursor = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.Images.Media.RELATIVE_PATH}, MediaStore.Images.Media.DISPLAY_NAME + "=? ",
                new String[]{fileName}, null);

        if (queryCursor != null && queryCursor.moveToFirst())
            Uri content = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendEncodedPath(queryCursor.getString(queryCursor.getColumnIndex(MediaStore.Images.Media.RELATIVE_PATH)))
            return content;
        } else
            return null;
        return null;

It saves the file to the storage, it can be seen with the Device Explorer in Android Studio. It is also uploaded to the cloud and can be viewed from there(if it is a new file). But when I'm trying to load it into a ImageView with Glide, it gives me an error: java.lang.UnsupportedOperationException: Unknown or unsupported URL: content://. And I can't seem to figure out why. It used to work and the URI should be correct as it is used on other places as well(uploading the file, saving the file, etc.) and it works. What is the problem with Glide/my code?

Full error:

E/GlideExecutor: Request threw uncaught throwable
java.lang.UnsupportedOperationException: Unknown or unsupported URL: content://media/external/images/media/Pictures/**AppName**/IMG20200112164646.jpg
    at android.database.DatabaseUtils.readExceptionFromParcel(
    at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(
    at android.content.ContentProviderProxy.openTypedAssetFile(
    at android.content.ContentResolver.openTypedAssetFileDescriptor(
    at android.content.ContentResolver.openAssetFileDescriptor(
    at android.content.ContentResolver.openInputStream(
    at com.bumptech.glide.load.engine.SourceGenerator.startNext(
    at com.bumptech.glide.load.engine.DecodeJob.runGenerators(
    at com.bumptech.glide.load.engine.DecodeJob.runWrapped(
    at java.util.concurrent.ThreadPoolExecutor.runWorker(
    at java.util.concurrent.ThreadPoolExecutor$
    at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$


Your getUriFromContentResolver() is wrong. Query for the _ID, then use ContentUris.withAppendedId() to assemble the Uri to use.

For example, in this sample app from this book, I use:

  suspend fun getLocalUri(filename: String): Uri? =
    withContext(Dispatchers.IO) {
      val resolver = context.contentResolver

      resolver.query(collection, PROJECTION, QUERY, arrayOf(filename), null)
        ?.use { cursor ->
          if (cursor.count > 0) {
            return@withContext ContentUris.withAppendedId(


where PROJECTION and QUERY are:

private val PROJECTION = arrayOf(MediaStore.Video.Media._ID)
private const val QUERY = MediaStore.Video.Media.DISPLAY_NAME + " = ?"

and where collection is:

  private val collection =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) MediaStore.Video.Media.getContentUri(
    ) else MediaStore.Video.Media.EXTERNAL_CONTENT_URI

(in my case, I am querying videos; you would use MediaStore.Images instead)