My app contains a listview which can optionally contain images from a users sd card. It works fine however when any image is loaded there is noticeable lag. I have this in my getView:
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image, o);
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap myBitmap = BitmapFactory.decodeFile(image, o2);
image_main.setImageBitmap(myBitmap);
Any suggestions?
EDIT: Replaced the above with this but no images are loading…
class Thumbnailer extends AsyncTask<String, Void, Bitmap> {
String image;
@Override
protected void onPostExecute(Bitmap result) {
image_main.setImageBitmap(result);
}
@Override
protected void onProgressUpdate(Void... progress) {
}
@Override
protected Bitmap doInBackground(String... params) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image, o);
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeFile(image, o2);
}
}
new Thumbnailer().execute(image);
Show the row with a placeholder image. Do your
BitmapFactorywork in anAsyncTask, updating theImageViewwhen done (if theImageViewhasn’t been recycled and so still needs this particular thumbnail). Cache your work so you do not have to re-do all the scaling again, at least for this incarnation of theListView, perhaps longer if the images will not be changing.