简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM