android.below の URL から画像をフェッチするときに OutOfMemoryError が発生しました。コードと例外について説明します。
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
URL url = null;
try {
url = new URL(image);
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 )
{
bais.write(byteChunk, 0, n);
}
is.close();
bais.flush();
} catch (Exception e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
bais = null; // Perform any other exception handling that's appropriate.
}
例外ログ: 上記のコードに対して生成された
03-22 13:04:44.858: E/dalvikvm-heap(1528): Out of memory on a 13131140-byte allocation. 03-22 13:04:44.858: I/dalvikvm(1528):
> "Thread-180" prio=5 tid=25 RUNNABLE 03-22 13:04:44.858:
> I/dalvikvm(1528):|group="main" sCount=0 dsCount=0
> obj=0x415deed8self=0x378150 03-22 13:04:44.858: I/dalvikvm(1528): |
> sysTid=1572 nice=0 sched=0/0 cgrp=[fopen-error:2]handle=1723384 03-22
> 13:04:44.858: I/dalvikvm(1528): | schedstat=( 765401358 258475984 4706
> ) utm=41 stm=35 core=0 03-22 13:04:44.858: I/dalvikvm(1528): at
> java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~91)
> 03-22 13:04:44.858: I/dalvikvm(1528): at
> java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
> 03-22 13:04:44.858: I/dalvikvm(1528): at
> com.lukup.util.FetchImage.run(FetchImage.java:46) 03-22 13:04:44.858:
> W/dalvikvm(1528): threadid=25: thread exiting with uncaught
> exception(group=0x409df1f8) 03-22 13:04:44.868:
> E/AndroidRuntime(1528): FATAL EXCEPTION: Thread-180 03-22
> 13:04:44.868: E/AndroidRuntime(1528): java.lang.OutOfMemoryError 03-22
> 13:04:44.868: E/AndroidRuntime(1528): at
> java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
> 03-22 13:04:44.868: E/AndroidRuntime(1528): at `enter code
> here`java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
> 03-22 13:04:44.868: E/AndroidRuntime(1528): at
> com.lukup.util.FetchImage.run(FetchImage.java:46)
> --
上記は例外ログです