I have a ListView
and I'm playing with Palette
from the support library. When on using BitmapFactory.decodeStream
to generate a bitmap from a url, this throws an exception (Network on UI thread) or possibly very expensive. How do I make this asynchronous? I couldn't think of any efficient way to do this. What's the best approach?
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_grid, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.img_photo);
holder.bg = (LinearLayout) convertView.findViewById(R.id.bg_title);
holder.text = (TextView) convertView.findViewById(R.id.txt_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Picasso.with(mContext)
.load(mShows.get(position).poster)
.into(holder.image);
try {
URL url = new URL(mShows.get(position).poster);
Bitmap bitmap = BitmapFactory.decodeStream(
url.openConnection().getInputStream()); // Too expensive!!!
Palette palette = Palette.generate(bitmap);
holder.text.setText(mShows.get(position).title);
holder.text.setTextColor(palette.getVibrantColor().getRgb());
holder.bg.setAlpha(0.4f);
holder.bg.setBackgroundColor(palette.getDarkMutedColor().getRgb());
} catch (IOException e) {
e.printStackTrace();
}
return convertView;
}