How to cache a bitmap on android?

Asked

Viewed 243 times

1

Hello, I’m making an application for my tcc, at the moment it is searching a list of images in the database and showing in a listview on android, but when I transition list, it does search again, this makes the application get very heavy, so I’d like to cache the bitmap, so when I open the app it uses the images you downloaded. I’m taking a byte array and transforming it into bitmap, this in a baseAdapter and I would like to know how to cache it.

public class UsuarioAdapter extends BaseAdapter {
    private List<Usuario> usrs;
    private Context context;
    private LayoutInflater inflater;

public UsuarioAdapter(Context context, List<Usuario> usrs,
        ImageLoader mImageLoader) {
    this.usrs = usrs;
    this.context = context;
    this.inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.mImageLoader = mImageLoader;

}

@Override
public int getCount() {
    return usrs.size();
}

@Override
public Object getItem(int arg0) {
    return usrs.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return usrs.get(arg0).getId();
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder = null;

    if (view == null) {
        holder = new ViewHolder();
        int layout = R.layout.lista_de_usuarios;
        view = inflater.inflate(layout, null);
        view.setTag(holder);

        holder.ivFoto = (ImageView) view.findViewById(R.id.ivLvFoto);
        holder.tvNome = (TextView) view.findViewById(R.id.tvLvNome);
        holder.tvIdade = (TextView) view.findViewById(R.id.tvLvIdade);

    } else {
        holder = (ViewHolder) view.getTag();
    }
    Usuario usr = usrs.get(position);

    holder.tvNome.setText(usr.getNome());
    holder.tvIdade.setText(usr.getIdade() + " Anos");

    Bitmap bitmap = BitmapFactory.decodeByteArray(usr.getFoto(), 0,
            usr.getFoto().length);
    holder.ivFoto.setImageBitmap(bitmap);

    return view;
}

static class ViewHolder {
    ImageView ivFoto;
    TextView tvNome;
    TextView tvIdade;
}

}

The bitmap I refer to is in that line of the code :

 Bitmap bitmap = BitmapFactory.decodeByteArray(usr.getFoto(), 0,
 usr.getFoto().length);
 holder.ivFoto.setImageBitmap(bitmap);

2 answers

1

There are several ways to do this on Android. But don’t keep reinventing the wheel. There are numerous frameworks ready to do this. Among them I recommend the

You can get tutorials of any of these with a simple Google search. In order not to waste time I would use Picasso which is very simple, just use his Gradle or Jar and with a single line you already get what you want. But if you want to specialize in Android dev I strongly recommend studying Volley.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.