我有一個簡單的問題:雖然我正確使用了sampleSize,但我的代碼甚至沒有達到BitmapFactory
代碼,因爲DefaultHttpClient
已經在拋出異常。OutOfMemoryError通過DefaultHttpClient加載位圖
這裏是我的代碼:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(mSongInfo.imageLarge);
HttpResponse response = client.execute(request);
int sampleSize = 1;
while (response.getEntity().getContentLength()/sampleSize
/sampleSize > 100 * 1024) {
sampleSize *= 2;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
final Bitmap bitmap = BitmapFactory.decodeStream(response
.getEntity().getContent(), null, options);
這裏是例外:
0 java.lang.OutOfMemoryError: (Heap Size=11463KB, Allocated=7623KB, Bitmap Size=9382KB)
1 at org.apache.http.util.ByteArrayBuffer.<init>(ByteArrayBuffer.java:53)
2 at org.apache.http.impl.io.AbstractSessionInputBuffer.init(AbstractSessionInputBuffer.java:82)
3 at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:98)
4 at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
5 at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
6 at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
7 at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
8 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:173)
9 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
12 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
13 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
14 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
15 at de.goddchen.android.easysongfinder.fragments.SongFragment$1.run(SongFragment.java:79)
16 at java.lang.Thread.run(Thread.java:1027)
正如你看到的,代碼甚至沒有達到其中i檢查大小的部分(內容 - 長度)並計算適當的樣本大小。
我不知道簡單地調用DefaultHttpClient.execute(...)
已經將完整的內容加載到內存中。
我做錯了什麼?首先檢索內容長度然後開始閱讀InputStream
的內容的正確方法是什麼?
編輯 避免常見的答案來說明如何從URL加載圖像:我已經知道該怎麼做,我也貼上面的代碼,那麼爲什麼你一直對參考教程?我明確地明確了這個問題:爲什麼HttpClient.execute(...)
已經獲取了整個內容並將其存儲在內存中,而不是向我提供合適的InputStream
?請不要發佈任何關於如何從URL加載Bitmap
的初學者教程...
是包括'內容Length'頭的HTTP響應?你測試了什麼環境(設備與模擬器,操作系統版本等)? – CommonsWare
是的,它提供了適當的內容長度。我正在從薑餅到果凍豆等真實設備收到這些錯誤...... – Goddchen