0
public Object fetch(String address) throws MalformedURLException,
IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}  

private Drawable ImageOperations(Context ctx, String url) {
    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
    catch (Exception e) 
    {
        return null;
    }
}

try {
            Drawable a =ImageOperations(this,"url"); imgView.setImageDrawable(a);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();

This works, but on rare ocasions the app freezes due to a "SocketException: Adress family not supported by protocol". Is there any way to fix this? Thanks

Johan
  • 2,149
  • 4
  • 21
  • 18

2 Answers2

0

You are trying to Download a File from the UI Thread...(which is why your UI Freezes)

Use a Seperate Thread or AsyncTask so that your UI doesn't Freeze up.

This should solve your problem.

st0le
  • 33,375
  • 8
  • 89
  • 89
  • Ok, Ive tried with the first answer in this thread: http://stackoverflow.com/questions/3090650/android-loading-an-image-from-the-web-with-asynctask, but the "DownloadImageTask"-part of "new DownloadImageTask.execute(mChart);" gets red in eclipse, even though the class is created. Did i miss something? – Johan Jan 12 '11 at 12:45
0

As st0le has pointed out you are trying to do the heavy duty stuff from the UI thread.

All heavy-duty stuff in Android should be done on other worker thread. Because doing it in main thread (or the UI thread) can make your application unresponsive and may be killed as the system is persuaded to think that it has hung.

So you have to do the long running operations in separate thread. For implementing this you can use the concept of Handlers.

Navaneeth Sen
  • 6,315
  • 11
  • 53
  • 82