2011-01-05 12 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が特定のURLで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); 
    } 

そしてOSは、代わりにあなたはもちろんのことをログに記録する(設定1のデフォルトサイズを使用するので、より8Kにバッファサイズを設定していないことを確認しますが、それに気づくのに私はしばらくかかりました;))。

+0

を使用している、それは2.xの中でまだ残っているのですか?私のテストではそうだが、私はGoogleから正式な確認を求めている。また、あなたのコードでは、BUFFER_IO_SIZEに何を設定しますか? – ThomasW

+0

@ThomasW確かにわかりません。私が確信していることは、エミュレータとデバイスの両方で2.1と2.2で同じ動作と同じ修正が私のために働いたということです。私はBUFFER_IO_SIZEの値を含めるように答えを更新します。 – mcveat

+0

ソリューションをありがとう、それは動作します。 – sat

関連する問題