I have a custom list view with an image. I need to set the source of the image via a url but I don't want the process to block the UI so I'm using an Async task. However the images are being set on only one image on the list and it shows up like a slideshow.
Is there a better way to go about this?
Here is my code:
Custom Adapter
class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private int i = 0;
Contact[] myContact;
String imageURL;
public MyArrayAdapter(Context context, Contact[] contact) {
super(context, R.layout.custom_list);
this.context = context;
this.myContact = contact;
int s = myContact.length;
int k = contact.length;
}
@Override
public int getCount() {
return myContact.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_list, parent, false);
TextView contact_first_name = (TextView) rowView
.findViewById(R.id.first_name);
TextView contact_last_name = (TextView) rowView
.findViewById(R.id.last_name);
imageView = (ImageView) rowView.findViewById(R.id.photo);
imageURL = myContact[i].getImageUrl();
new LoadImageTask().execute(imageURL);
contact_first_name.setText(myContact[i].getFirstName());
contact_last_name.setText(myContact[i].getLastName());
i++;
return rowView;
}
}
Async Task
public class LoadImageTask extends AsyncTask<String, Integer, String> {
Bitmap bitmap;
@Override
protected String doInBackground(String... imageURL) {
// TODO Auto-generated method stub
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String line) {
try {
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}