I am loading an image from url and input it to my listview. The problem is that the imageview is changing it's image everytime I'm scrolling the listview.
I used this code from: How to load an ImageView by URL in Android? to load images from url:
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
In my ListAdapter i use this code to load up the image:
public View getView(int position, View convertView, ViewGroup parent){
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.thumb = (ImageView) convertView.findViewById(R.id.thumb);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
//holder.code = (TextView) convertView.findViewById(R.id.code);
convertView.setTag(holder);
}
else{
holder = (ViewHolderItem) convertView.getTag();
}
holder.name.setText(this.main.countries.get(position).title);
if (holder.thumb != null) {
new DownloadImageTask(holder.thumb).execute(this.main.countries.get(position).thumb);
}
return convertView;
}
In my main activity:
public void get_data(String data){
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++){
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.title = obj.getString("title");
add.thumb = obj.getString("artwork_url");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}