Sunday, May 2, 2010

Re: [android-developers] Re: Newb: Display URL Image

Jose Gomez wrote:
> If you are just trying to make the ImageView display an image from a URL
> use this function.
>
> private Bitmap decodeImage(String url) {
>
> URL aURL;
>
> try {
>
> aURL = new URL(url);
>
> URLConnection conn = aURL.openConnection();
>
> conn.connect();
>
> InputStream is = conn.getInputStream();
>
> BufferedInputStream bis = new BufferedInputStream(is);
>
> Bitmap bm = BitmapFactory.decodeStream(bis);
>
> bis.close();
>
> is.close();
>
> return bm;
>
> } catch (MalformedURLException e) {
>
> e.printStackTrace();
>
> } catch (IOException e) {
>
> e.printStackTrace();
>
> }
>
> return null;
>
> }
> }
>
>
> call the function as
> imgView.setImageBitmap(decodeImage("http://sss.jpg"));

The decodeImage() method you supply is fine. However, do not call it as
shown. That requires you to call it on the main application thread,
because you are updating the UI. It is not safe to make HTTP requests on
the main application thread, because you do not know how long they will
take to process.

One approach is to call decodeImage() in the doInBackground() method of
an AsyncTask, then update the ImageView in the task's onPostExecute().
Have the ImageView show some placeholder image at the outset, so while
the download is happening, the user sees something, which then gets
replaced by the real image once it is downloaded.

There's a lot more that an app should consider: caching, detecting
connectivity, doing something more with the exceptions than quietly
logging them, etc.

--
Mark Murphy (a Commons Guy)
http://commonsware.com | http://github.com/commonsguy
http://commonsware.com/blog | http://twitter.com/commonsguy

Android Consulting: http://commonsware.com/consulting

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment