Setting images to a listview is a big problem that either it may stuck or memory issue may happen,
In the adapter use the following,
- public class AsyncImageSetter extends AsyncTask<Void, Void, Bitmap> {
- private ImageView img;
- private int image_resId;
- private Context c;
- private boolean cancel = false;
- private int sampleSize;
- public AsyncImageSetter(Context c, ImageView img, int image_ResId) {
- this.img = img;
- this.image_resId = image_ResId;
- this.c = c;
- }
- public void cancel() {
- cancel = true;
- }
- @Override
- protected void onPreExecute() {
- /*--- we hide the Views from the user until the content is ready. This will prevent
- * the user from seeing an image being "transformed" into the next one (as a result of
- * View recycling) on slow devices.
- */
- //img.setVisibility(View.GONE);
- super.onPreExecute();
- }
- @Override
- protected Bitmap doInBackground(Void... params) {
- if (!cancel) {
- try {
- return decodeAndScale();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- @Override
- protected void onPostExecute(Bitmap result) {
- //img.setVisibility(View.VISIBLE);
- try {
- img.setImageBitmap(result);
- } catch (Exception e) {
- /*--- show an error icon in case something went wrong ---*/
- img.setImageResource(R.drawable.close);
- }
- super.onPostExecute(result);
- }
- private Bitmap decodeAndScale() {
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = setSampleSize();
- return BitmapFactory.decodeResource(c.getResources(), image_resId,
- options);
- }
- private int setSampleSize() {
- // TODO add multiple screens check
- /*--- modify this method to match your needs ---*/
- if (getScreenWidth((Activity) c) >= 320) {
- /*--- physical width >= 480px ---*/
- sampleSize = 2;
- }
- return sampleSize;
- }
- public static int getScreenWidth(Activity a) {
- Display display = a.getWindowManager().getDefaultDisplay();
- DisplayMetrics outMetrics = new DisplayMetrics();
- display.getMetrics(outMetrics);
- float density = a.getResources().getDisplayMetrics().density;
- float dpWidth = outMetrics.widthPixels / density;
- return (int) dpWidth;
- }
- }
- cell.imageloader = new AsyncImageSetter(context, cell.doctorImage,
- mImageResources[position]);
