2011-01-12 123 views
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(); 

這工作,但在罕見ocasions應用程序凍結由於「SocketException:ADRESS家人不支持協議」。有沒有什麼辦法解決這一問題?由於問題加載圖像

回答

0

您正在嘗試下載從UI線程文件...(這就是爲什麼你的UI凍結)

使用單獨的線程或AsyncTask使您的用戶界面不會凍結。

這應該可以解決您的問題。

+0

好吧,我試着用這個線程的第一個答案:http://stackoverflow.com/questions/3090650/android-loading-an-image-from-the-web-with-asynctask,但「DownloadImageTask」 - 新的DownloadImageTask.execute(mChart);「在eclipse中獲得紅色,即使創建了該類。我錯過了什麼? – Johan 2011-01-12 12:45:10

0

正如st0le指出的那樣,您正試圖從UI線程中完成重型任務。

Android中的所有重型應用程序都應該在其他worker thread上完成。因爲在main thread(或UI線程)中執行此操作可能會使您的應用程序無響應,並且可能會在系統被認爲已掛起時被殺死。

所以你必須在單獨的線程中做長時間運行的操作。爲了實現這個,你可以使用Handlers的概念。