How to retrieve images from a remote server in Android
The code below is what I use to retrieve images from a remote server, but the problem is the image doesn't show always. The image will only appear 5/7. Is there anything I am doing wrong? And also I am using LazyList (Lazy load of images in ListView) created by Fedor and I noticed that this never happens to it
ImageView mainImageView = (ImageView) findViewById(R.id.picture);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
String imageurl = "http://www.yoururl/cutecats.png";
ImageDownloadMessageHandler imageDownloadMessageHandler1= new ImageDownloadMessageHandler(progressBar, mainImageView);
ImageDownlaodThread imageDownlaodThread = new ImageDownlaodThread(imageDownloadMessageHandler1,imageurl);
imageDownlaodThread.sta开发者_如何学Crt();
}
class ImageDownlaodThread extends Thread {
ImageDownloadMessageHandler imageDownloadMessageHandler;
String imageUrl;
public ImageDownlaodThread(ImageDownloadMessageHandler imageDownloadMessageHandler, String imageUrl) {
this.imageDownloadMessageHandler = imageDownloadMessageHandler;
this.imageUrl = imageUrl;
}
@Override
public void run() {
Drawable drawable = LoadImageFromWebOperations(imageUrl);
Message message = imageDownloadMessageHandler.obtainMessage(1, drawable);
imageDownloadMessageHandler.sendMessage(message);
System.out.println("Message sent");
}
}
class ImageDownloadMessageHandler extends Handler {
ProgressBar progressBar;
View imageTextView;
public ImageDownloadMessageHandler(ProgressBar progressBar, View imageTextView) {
this.progressBar = progressBar;
this.imageTextView = imageTextView;
}
@Override
public void handleMessage(Message message) {
progressBar.setVisibility(View.GONE);
imageTextView.setBackgroundDrawable(((Drawable) message.obj));
imageTextView.setVisibility(View.VISIBLE);
}
}
Drawable LoadImageFromWebOperations(String url) {
Drawable d = null;
InputStream is = null;
try {
is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
public void onBackPressed(){
captains1.this.finish();
overridePendingTransition(R.anim.hold, R.anim.fadeout);
return;
}
I made an Android open source class to manage pictures, maybe you can solve your problem with it: http://code.google.com/p/imagemanager/
精彩评论