我从 json 获取图像作为列表视图。
json 中的所有文本都显示正常,但无法显示图像。在logcat中,它显示Out of memory error
我认为图像加载和内存缓存存在问题。
下面是我的图像加载器和内存缓存类和 logcat。
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_image;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
System.out.println("OutOfMemoryError " +ex);
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
MemoryCache.java
public class MemoryCache {
private static final String TAG = "MemoryCache";
// Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// Current allocated size
private long size = 0;
// Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
// Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// Least recently accessed item will be the first one iterated
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
这是我的日志:
06-11 11:22:27.910: D/dalvikvm(526): GC freed 1102 objects / 244576 bytes in 174ms
06-11 11:25:55.619: D/AndroidRuntime(541): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
06-11 11:25:55.629: D/AndroidRuntime(541): CheckJNI is ON
06-11 11:25:55.909: D/AndroidRuntime(541): --- registering native functions ---
06-11 11:25:56.390: D/ddm-heap(541): Got feature list request
06-11 11:25:56.949: D/PackageParser(63): Scanning package: /data/app/vmdl38984.tmp
06-11 11:25:57.320: I/PackageManager(63): Removing non-system package:com.androidbegin.jsonparsetutorial
06-11 11:25:57.329: D/PackageManager(63): Removing package com.androidbegin.jsonparsetutorial
06-11 11:25:57.329: D/PackageManager(63): Activities: com.androidbegin.jsonparsetutorial.MainActivity com.androidbegin.jsonparsetutorial.SingleItemView
06-11 11:25:57.480: D/PackageManager(63): Scanning package com.androidbegin.jsonparsetutorial
06-11 11:25:57.490: I/PackageManager(63): /data/app/vmdl38984.tmp changed; unpacking
06-11 11:25:57.511: D/installd(31): DexInv: --- BEGIN '/data/app/vmdl38984.tmp' ---
06-11 11:25:59.039: D/dalvikvm(547): DexOpt: load 200ms, verify 799ms, opt 32ms
06-11 11:25:59.079: D/installd(31): DexInv: --- END '/data/app/vmdl38984.tmp' (success) ---
06-11 11:25:59.091: D/PackageManager(63): Activities: com.androidbegin.jsonparsetutorial.MainActivity com.androidbegin.jsonparsetutorial.SingleItemView
06-11 11:25:59.100: D/ActivityManager(63): Uninstalling process com.androidbegin.jsonparsetutorial
06-11 11:25:59.100: D/ActivityManager(63): Force removing process ProcessRecord{43db9e78 526:com.androidbegin.jsonparsetutorial/10026} (com.androidbegin.jsonparsetutorial/10026)
06-11 11:25:59.100: I/Process(63): Sending signal. PID: 526 SIG: 9
06-11 11:25:59.159: D/ActivityManager(63): Received spurious death notification for thread android.os.BinderProxy@43cc72e0
06-11 11:25:59.339: I/installd(31): move /data/dalvik- cache/data@app@vmdl38984.tmp@classes.dex -> /data/dalvik-cache/data@app@com.androidbegin.jsonparsetutorial.apk@classes.dex
06-11 11:25:59.350: D/PackageManager(63): New package installed in /data/app/com.androidbegin.jsonparsetutorial.apk
06-11 11:25:59.549: D/AndroidRuntime(541): Shutting down VM
06-11 11:25:59.549: D/dalvikvm(541): DestroyJavaVM waiting for non-daemon threads to exit
06-11 11:25:59.560: D/dalvikvm(541): DestroyJavaVM shutting VM down
06-11 11:25:59.570: D/dalvikvm(541): HeapWorker thread shutting down
06-11 11:25:59.570: D/dalvikvm(541): HeapWorker thread has shut down
06-11 11:25:59.570: D/jdwp(541): JDWP shutting down net...
06-11 11:25:59.570: I/dalvikvm(541): Debugger has detached; object registry had 1 entries
06-11 11:25:59.570: D/dalvikvm(541): VM cleaning up
06-11 11:25:59.610: D/ActivityManager(63): Uninstalling process com.androidbegin.jsonparsetutorial
06-11 11:25:59.610: E/AndroidRuntime(541): ERROR: thread attach failed
06-11 11:25:59.624: D/dalvikvm(541): LinearAlloc 0x0 used 623012 of 5242880 (11%)
06-11 11:26:00.270: D/dalvikvm(63): GC freed 7834 objects / 550336 bytes in 376ms
06-11 11:26:00.299: W/ResourceType(63): Resources don't contain package for resource number 0x7f0700e5
06-11 11:26:00.329: W/ResourceType(63): Resources don't contain package for resource number 0x7f020031
06-11 11:26:00.329: W/ResourceType(63): Resources don't contain package for resource number 0x7f020030
06-11 11:26:00.329: W/ResourceType(63): Resources don't contain package for resource number 0x7f050000
06-11 11:26:00.409: W/ResourceType(63): Resources don't contain package for resource number 0x7f060001
06-11 11:26:00.499: W/ResourceType(63): Resources don't contain package for resource number 0x7f060000
06-11 11:26:00.810: W/ResourceType(63): Resources don't contain package for resource number 0x7f0700e5
06-11 11:26:00.820: W/ResourceType(63): Resources don't contain package for resource number 0x7f020031
06-11 11:26:00.820: W/ResourceType(63): Resources don't contain package for resource number 0x7f020030
06-11 11:26:00.820: W/ResourceType(63): Resources don't contain package for resource number 0x7f050000
06-11 11:26:00.860: W/ResourceType(63): Resources don't contain package for resource number 0x7f060001
06-11 11:26:00.869: D/dalvikvm(143): GC freed 183 objects / 8056 bytes in 569ms
06-11 11:26:00.869: W/ResourceType(63): Resources don't contain package for resource number 0x7f060000
06-11 11:26:01.430: D/AndroidRuntime(552): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
06-11 11:26:01.459: D/AndroidRuntime(552): CheckJNI is ON
06-11 11:26:01.879: D/AndroidRuntime(552): --- registering native functions ---
06-11 11:26:02.409: D/ddm-heap(552): Got feature list request
06-11 11:26:02.929: I/ActivityManager(63): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.androidbegin.jsonparsetutorial/.MainActivity }
06-11 11:26:03.030: D/AndroidRuntime(552): Shutting down VM
06-11 11:26:03.030: D/dalvikvm(552): DestroyJavaVM waiting for non-daemon threads to exit
06-11 11:26:03.039: D/dalvikvm(552): DestroyJavaVM shutting VM down
06-11 11:26:03.039: D/dalvikvm(552): HeapWorker thread shutting down
06-11 11:26:03.050: D/dalvikvm(552): HeapWorker thread has shut down
06-11 11:26:03.050: D/jdwp(552): JDWP shutting down net...
06-11 11:26:03.050: I/dalvikvm(552): Debugger has detached; object registry had 1 entries
06-11 11:26:03.050: D/dalvikvm(552): VM cleaning up
06-11 11:26:03.100: I/ActivityManager(63): Start proc com.androidbegin.jsonparsetutorial for activity com.androidbegin.jsonparsetutorial/.MainActivity: pid=559 uid=10026 gids={3003, 1015}
06-11 11:26:03.110: E/AndroidRuntime(552): ERROR: thread attach failed
06-11 11:26:03.160: D/dalvikvm(552): LinearAlloc 0x0 used 638596 of 5242880 (12%)
06-11 11:26:03.440: D/ddm-heap(559): Got feature list request
06-11 11:26:03.480: D/dalvikvm(29): GC freed 310 objects / 12008 bytes in 351ms
06-11 11:26:04.049: D/dalvikvm(29): GC freed 52 objects / 2296 bytes in 514ms
06-11 11:26:04.219: D/dalvikvm(29): GC freed 2 objects / 56 bytes in 159ms
06-11 11:26:04.669: I/ActivityManager(63): Displayed activity com.androidbegin.jsonparsetutorial/.MainActivity: 1662 ms (total 1662 ms)
06-11 11:26:06.240: D/dalvikvm(559): GC freed 3046 objects / 226432 bytes in 104ms
06-11 11:26:06.300: I/MemoryCache(559): MemoryCache will use up to 4.0MB
06-11 11:26:06.990: W/System.err(559): java.net.MalformedURLException: Protocol not found: 192.168.1.52/projects/konnectplus_new/includes/marketing/comingsoon-medium.jpg
06-11 11:26:06.999: W/System.err(559): at java.net.URL.<init>(URL.java:275)
06-11 11:26:07.009: W/System.err(559): at java.net.URL.<init>(URL.java:159)
06-11 11:26:07.009: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.getBitmap(ImageLoader.java:67)
06-11 11:26:07.009: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.access$0(ImageLoader.java:57)
06-11 11:26:07.020: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader$PhotosLoader.run(ImageLoader.java:151)
06-11 11:26:07.020: W/System.err(559): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
06-11 11:26:07.020: W/System.err(559): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-11 11:26:07.020: W/System.err(559): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-11 11:26:07.020: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-11 11:26:07.030: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-11 11:26:07.030: W/System.err(559): at java.lang.Thread.run(Thread.java:1096)
06-11 11:26:07.039: W/System.err(559): java.net.MalformedURLException: Protocol not found: 192.168.1.52/projects/konnectplus_new/includes/marketing/rajini-medium.jpg
06-11 11:26:07.039: W/System.err(559): at java.net.URL.<init>(URL.java:275)
06-11 11:26:07.039: W/System.err(559): at java.net.URL.<init>(URL.java:159)
06-11 11:26:07.039: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.getBitmap(ImageLoader.java:67)
06-11 11:26:07.039: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.access$0(ImageLoader.java:57)
06-11 11:26:07.039: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader$PhotosLoader.run(ImageLoader.java:151)
06-11 11:26:07.049: W/System.err(559): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
06-11 11:26:07.049: W/System.err(559): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-11 11:26:07.049: I/System.out(559): **OutOfMemoryError java.net.MalformedURLException: Protocol not found: 192.168.*.***/projects/*********_new/includes/marketing/comingsoon-medium.jpg**
06-11 11:26:07.060: W/System.err(559): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-11 11:26:07.060: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-11 11:26:07.060: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-11 11:26:07.070: I/MemoryCache(559): cache size=0 length=1
06-11 11:26:07.070: W/System.err(559): at java.lang.Thread.run(Thread.java:1096)
06-11 11:26:07.080: W/System.err(559): java.net.MalformedURLException: Protocol not found: 192.168.1.52/projects/konnectplus_new/includes/marketing/BlastfromPast-medium.jpg
06-11 11:26:07.080: W/System.err(559): at java.net.URL.<init>(URL.java:275)
06-11 11:26:07.080: W/System.err(559): at java.net.URL.<init>(URL.java:159)
06-11 11:26:07.080: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.getBitmap(ImageLoader.java:67)
06-11 11:26:07.080: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.access$0(ImageLoader.java:57)
06-11 11:26:07.090: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader$PhotosLoader.run(ImageLoader.java:151)
06-11 11:26:07.090: W/System.err(559): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
06-11 11:26:07.090: W/System.err(559): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-11 11:26:07.090: W/System.err(559): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-11 11:26:07.099: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-11 11:26:07.099: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-11 11:26:07.099: W/System.err(559): at java.lang.Thread.run(Thread.java:1096)
06-11 11:26:07.099: I/System.out(559): **OutOfMemoryError java.net.MalformedURLException: Protocol not found: 192.168.*.**/projects/******88_new/includes/marketing/BlastfromPast-medium.jpg**
06-11 11:26:07.111: I/MemoryCache(559): cache size=0 length=2
06-11 11:26:07.111: I/System.out(559): **OutOfMemoryError java.net.MalformedURLException: Protocol not found: 192.168.*.**/projects/******8_new/includes/marketing/rajini-medium.jpg**
06-11 11:26:07.111: I/MemoryCache(559): cache size=0 length=3
**06-11 11:26:07.120: W/System.err(559): java.net.MalformedURLException: Protocol not found: 192.168.*.**/projects/******_new/includes/marketing/oneticketonemovie-medium.jpg**
06-11 11:26:07.120: W/System.err(559): at java.net.URL.<init>(URL.java:275)
06-11 11:26:07.143: W/System.err(559): at java.net.URL.<init>(URL.java:159)
06-11 11:26:07.143: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.getBitmap(ImageLoader.java:67)
06-11 11:26:07.143: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader.access$0(ImageLoader.java:57)
06-11 11:26:07.143: W/System.err(559): at com.androidbegin.jsonparsetutorial.ImageLoader$PhotosLoader.run(ImageLoader.java:151)
06-11 11:26:07.143: W/System.err(559): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
06-11 11:26:07.150: W/System.err(559): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-11 11:26:07.150: W/System.err(559): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-11 11:26:07.150: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-11 11:26:07.150: W/System.err(559): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-11 11:26:07.150: W/System.err(559): at java.lang.Thread.run(Thread.java:1096)
06-11 11:26:07.150: I/System.out(559): **OutOfMemoryError java.net.MalformedURLException: Protocol not found: 192.168.*.**/projects/******_new/includes/marketing/oneticketonemovie-medium.jpg**
06-11 11:26:07.163: I/MemoryCache(559): cache size=0 length=4
06-11 11:26:09.959: D/dalvikvm(280): GC freed 44 objects / 2112 bytes in 156ms
06-11 11:26:15.080: D/dalvikvm(143): GC freed 2205 objects / 129320 bytes in 204ms
06-11 11:28:14.110: W/KeyCharacterMap(559): No keyboard for id 0
06-11 11:28:14.110: W/KeyCharacterMap(559): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-11 11:28:14.300: W/InputManagerService(63): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@43d098f0 (uid=10026 pid=559)
06-11 11:28:14.459: W/KeyCharacterMap(143): No keyboard for id 0
06-11 11:28:14.459: W/KeyCharacterMap(143): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-11 11:28:19.940: D/dalvikvm(559): GC freed 2515 objects / 165976 bytes in 188ms
错误 :
06-11 11:26:07.150: I/System.out(559): **OutOfMemoryError java.net.MalformedURLException: Protocol not found: 192.168.*.**/projects/******_new/includes/marketing/oneticketonemovie-medium.jpg**