Sini Sini - 10 days ago 11
Android Question

Listview shows images in wrong positions when scrolling

I have a ListView which I am filling from server. Everything works fine but the single problem is that the downloaded images are shown in wrong item positions when scroll. Only after a few seconds then it shows the correct image on the right position.

Here is my ArrayAdapter class, which includes the AsynchTask:

public class ApplicationAdapter extends ArrayAdapter<Application> {
private List<Application> items;

public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}

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

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

View v = convertView;

if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}

Application app = items.get(position);

if (app != null) {
ImageView imageView = (ImageView) v.findViewById(R.id.appIcon);
TextView titleText = (TextView) v.findViewById(R.id.titleTxt);

if (imageView != null) {

String path_image = app.getImagePath();

// Call AsynchTask to load image into ImageView from path
DownloadImageTask1 d = new DownloadImageTask(imageView);
d.execute(path_image);
}


if (titleText != null) {

titleText.setText(app.getTitle());

}

}

return v;
}

private class DownloadImageTask1 extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImageTask1(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(getRoundedCornerBitmap(result));

}
}


Can somebody please guide me to the right direction? I am already working for days to solve this issue. Thanks!!!

Answer

This is because the ImageView is reused when the listview is scrolled. show a loading image in the listview onPreExecute. it woluld be better if you use some library like picasso for this. as it does all the work for you including saving the image in the catch