xRobot xRobot - 27 days ago 18
Android Question

Glide and java.lang.OutOfMemoryError

I am developing an app that show all album cover images of the songs. So I am using glide for loading and caching images and to avoid OutofMemoryError but I still get that error:

11-11 11:05:55.866 11120-11120/com.xrobot.andrew.musicalbumsE/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.xrobot.andrew.musicalbums, PID: 11120 java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available


This is my getView in the AlbumAdapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

RelativeLayout albumsLay = (RelativeLayout)songInf.inflate
(R.layout.album_layout, parent, false);
ImageView coverView = (ImageView)albumsLay.findViewById(R.id.song_cover);

//get song using position
Song currSong = songs.get(position);

if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
Glide.with(mContext).load("").placeholder(img).override(50,50).into(coverView);
}

albumsLay.setTag(position);
return albumsLay;
}

Answer

Try using Glide directly with the image path:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    RelativeLayout albumsLay = (RelativeLayout)songInf.inflate
            (R.layout.album_layout, parent, false);
    ImageView coverView = (ImageView)albumsLay.findViewById(R.id.song_cover);

    //get song using position
    Song currSong = songs.get(position);

    // If you are sure currSong.getCover() exists you can remove the if statement
    if(new File(currSong.getCover().exists))
        Glide.with(mContext).load(currSong.getCover()).override(50,50).into(coverView);


    albumsLay.setTag(position);
    return albumsLay;
}

And you could also use a holder for the view. This would reduce the memory usage:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     CoverHolder holder = null;
     if (convertView == null) {
         convertView = mInflater.inflate(R.layout.album_layout, null);
         holder = new CoverHolder();
         holder.coverView = (ImageView)convertView.findViewById(R.id.song_cover);
         convertView.setTag(holder);
     } else {
         holder = (CoverHolder)convertView.getTag();
     }
    Glide.with(mContext).load(currSong.getCover()).override(50,50).into(holder.coverView);
    return convertView;
}

// The holder
public static class CoverHolder{
    public ImageView coverView;
}

Still, if you really need performance on a huge list. You can take a look at the RecyclerView here.