2011-01-05 44 views
9
 
public class TestButton extends Activity { 
    /** Called when the activity is first created. */ 
    ImageButton imgBtn; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     imgBtn = (ImageButton) findViewById(R.id.image); 
     //String url = "http://thenextweb.com/apps/files/2010/03/google_logo.jpg"; 
     String url1 = "http://trueslant.com/michaelshermer/files/2010/03/evil-google.jpg"; 
     Drawable drawable = LoadImage(url1); 
     imgBtn.setImageDrawable(drawable); 
    } 

    private Drawable LoadImage(String url) { 
     try { 
      InputStream is = (InputStream) new URL(url).getContent(); 
      Drawable d = Drawable.createFromStream(is, "src"); 
      return d; 
     } catch (Exception e) { 
      return null; 
     } 
    } 
} 

以上是我用來從web加載圖像到ImageButton中的代碼片段。大部分圖像都會顯示出來,但某些url像上面那樣,即url1,Drawable.createFromStream返回null!什麼原因,如何避免或克服這個問題?Android中的CreateFromStream返回null爲特定的網址

回答

12

我今天偶然發現了同樣的問題。並找到了答案,幸運的是:)有一個bug in SDK, described more or less on that google groups thread

解決方法爲我工作是:

 private static final int BUFFER_IO_SIZE = 8000; 

    private Bitmap loadImageFromUrl(final String url) { 
     try { 
      // Addresses bug in SDK : 
      // http://groups.google.com/group/android-developers/browse_thread/thread/4ed17d7e48899b26/ 
      BufferedInputStream bis = new BufferedInputStream(new URL(url).openStream(), BUFFER_IO_SIZE); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_IO_SIZE); 
      copy(bis, bos); 
      bos.flush(); 
      return BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size()); 
     } catch (IOException e) { 
      // handle it properly 
     } 
    } 

    private void copy(final InputStream bis, final OutputStream baos) throws IOException { 
     byte[] buf = new byte[256]; 
     int l; 
     while ((l = bis.read(buf)) >= 0) baos.write(buf, 0, l); 
    } 

而且確保不緩衝區的大小設置爲大於8K,因爲操作系統將使用的,而不是你設置(記錄該過程的一個默認大小,但我花了一段時間才注意到這一點;))。

+0

該缺陷是在安卓1.0版本,它仍然是圍繞2.X?在我的測試中,似乎是這種情況,但我正在尋求Google的官方確認。另外,在你的代碼中,你將BUFFER_IO_SIZE設置爲什麼? – ThomasW 2011-02-04 07:02:38

+0

@ThomasW無法確定。我敢肯定的兩件事情是它在模擬器和設備上具有相同的行爲和相同的修復功能,適用於2.1和2.2版本。我會更新我的答案以包含BUFFER_IO_SIZE值。 – mcveat 2011-02-04 08:18:09

+0

感謝您的解決方案,它的工作原理。 – sat 2011-02-10 09:39:42