I am trying to create a custom List Adapter which has an Image for every item it needs to download from the internet. When I first enter the Activity - the app freezes for a while till the images are downloaded and then the Activity List is loaded.
As I can make out the images are being downloaded before the activity loads. How can I download the images after the activity has loaded. I think I need to use Async Task. But since I am loading the images in the Custom Array Adapter not sure how to do it.
This is my Custom Adapter's getView()
:
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item_default, null);
}
Item p = items.get(position);
if (p != null) {
TextView list_title = (TextView) v.findViewById(R.id.list_title);
TextView list_description = (TextView) v
.findViewById(R.id.list_description);
TextView list_timestamp = (TextView) v
.findViewById(R.id.list_timestamp);
ImageView list_image = (ImageView) v.findViewById(R.id.list_image);
if (list_title != null) {
list_title.setText(p.getItemTitle());
}
if (list_description != null) {
list_description.setText(p.getItemDescription());
}
if (list_timestamp != null) {
list_timestamp.setText(p.getItemTimestamp());
}
if (list_image != null) {
Log.d("bMobile", "inside getView() image");
try {
URL imageURL = new URL(p.getItemImage());
HttpURLConnection con = (HttpURLConnection) imageURL
.openConnection();
InputStream inputStrem = con.getInputStream();
Bitmap image = BitmapFactory.decodeStream(inputStrem);
if (null != image)
list_image.setImageBitmap(image);
else
Log.d("bMobile", "Bitmap is Null");
} catch (Exception e) {
}
}
}
return v;
}
AsyncTask:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
@Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…