android imageview from url problem
I am using the following code to display images from an url in my imageview:
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
return null;
}
}
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
I have a timer that changes the image every 5th second. But in some rare cases the app freezes.开发者_如何转开发 Is it because the LoadImageFromWebOperations fails to load the image? Or any ideas what the problem might be, and how to fix it? Thanks!
You are blocking the UI Thread by using createFromStream() and that's why the app freezes occasionally.
What you need to do is loading the image in AsyncTask doInBackground() and onPostExecute you would set the Drawable. Also you need another placeholder (usually a spinner) while the AsyncTask is downloading from the web
精彩评论