I have an ImageAdapter that is loading thumbnails into a gridView.
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
LoadThumbs downloader = new LoadThumbs(imageView);
downloader.execute(Loggedin.mImageIds.get(position));
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
mImageIds is a string ArrayList with url's of images on my server. My LoadThumbs class just downloads images in an asynctask.
public class LoadThumbs extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference;
public LoadThumbs(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
protected Bitmap doInBackground(String... params) {
url = params[0];
try {
return BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Bitmap result) {
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
}
}
}
protected void onPreExecute() {
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageResource(R.drawable.loadcircle);
}
}
}
}
It works, it downloads the images. But then when I rotate the screen the images appear in reversed order.
There were several discussions on this already, but those didn't work for me. They would either redownload all the images when rotating the device or wouldn't work at all.
I was thinking of maybe putting the images in a bytearray and when convertView != null get them out of that bytearray instead of redownloading. But I can certainly use help with this. There has to be something with the way my getView works.
Thanks