Reputation: 5016
I want to load list of images into a listview from internet. Each list item contains a textview (i.e url of image) and an imageview. Here is my adapter class code to download images and bind to listview. But Images are getting mismatched with the urls. Few rows having the same image (but different urls). And some rows are changing its image after a while. Please help me out.
public class CustomAdapter extends BaseAdapter{
private Activity act;
private String imageUrlsArray[];
private LayoutInflater inflater;
public CustomAdapter(Activity activity, String imageUrls[]) {
this.act = activity;
this.imageUrlsArray = imageUrls;
inflater = (LayoutInflater)this.act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return imageUrlsArray.length;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
rowView = inflater.inflate(R.layout.list_row, parent, false);
holder = new ViewHolder();
holder.imageView = (ImageView)rowView.findViewById(R.id.imageViewInListRow);
holder.urlTextView = (TextView)rowView.findViewById(R.id.textViewInListRow);
rowView.setTag(holder);
}else{
holder = (ViewHolder) rowView.getTag();
}
loadImage(holder.imageView, imageUrlsArray[position]);
holder.urlTextView.setText(imageUrlsArray[position]);
return rowView;
}
private void loadImage(ImageView iv, String url) {
DownloadTask asyncTask = new DownloadTask();
asyncTask.execute(iv, url);
}
class DownloadTask extends AsyncTask<Object,Object, Object>{
private ImageView iv;
private InputStream is = null;
private Drawable imageDrawable = null;
@Override
protected Object doInBackground(Object... params) {
iv = (ImageView) params[0];
try {
is = new DefaultHttpClient().execute(new HttpPost(params[1].toString())).getEntity().getContent();
imageDrawable = Drawable.createFromStream((InputStream)is , "src name");
} catch (Exception e) {
e.printStackTrace();
}
return imageDrawable;
}
@Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
if(response != null){
iv.setImageDrawable((Drawable)response);
}
}
}
static class ViewHolder{
public TextView urlTextView;
public ImageView imageView;
}
}
Upvotes: 0
Views: 2009
Reputation: 6277
Use hashMap for proper mapping with textview. And First Convert url into Image Bitmap in Adapter only.
Upvotes: 2