キャッシュを介してリストビューに画像を表示するために LazyListAdapter を実装しているという問題があり、うまく機能していますが、outofMemoryError: メモリが使い果たされている場合があります。どうしてか分かりません?解決策を提案してください。
コード:
package com.TCC.android.adapters;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.TCC.android.R;
import com.TCC.android.collections.BrandListCollection;
import com.TCC.android.collections.CatedoryListCollection;
import com.TCC.android.collections.PriceListCollection;
public class PriceListLazyAdapter extends BaseAdapter {
private Activity activity;
// private List<BaseInventoryItem> localItems;
private LayoutInflater inflater = null;
private ImageLoader imageLoader;
public static Long id;
public static int cat_id;
public static String type;
PriceListCollection priceList = PriceListCollection.getSingletonObject();
// Pass in the list of items to adapt
public PriceListLazyAdapter(Activity inputActivity) {
activity = inputActivity;
// localItems = inputItems;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return priceList.getDisplayNames().size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.price_item, null);
}
// Grab all of the layout elements in which we need ot insert content.
TextView tvDisplayName = (TextView) vi.findViewById(R.id.tv_PriceItem_Name);
TextView tvRating1 = (TextView) vi.findViewById(R.id.tv_PriceItem_Rating1);
TextView tvPrice1 = (TextView) vi.findViewById(R.id.tv_PriceItem_Price1);
TextView tvMPG1 = (TextView) vi.findViewById(R.id.tv_PriceItem_MPG1);
TextView tvYear1 = (TextView) vi.findViewById(R.id.tv_PriceItem_Year1);
ImageView productImage = (ImageView) vi.findViewById(R.id.img_PriceItem);
/* ArrayList<String> arr = catList.getMapRating().get("Toyota Paseo");
System.out.println("The array================================>"+arr.get(0));
System.out.println("The array================================2>"+arr.get(1));*/
/*tvRating1.setText(catList.getMapRating().get(position).get(0));
tvRating2.setText(catList.getMapRating().get(position).get(1));
tvPrice1.setText(catList.getMapPrice().get(position).get(0));
tvPrice2.setText(catList.getMapPrice().get(position).get(1));
tvMPG1.setText(catList.getMapMpg().get(position).get(0));
tvMPG2.setText(catList.getMapMpg().get(position).get(1));
tvYear1.setText(catList.getMapYears().get(position).get(0));
tvYear2.setText(catList.getMapYears().get(position).get(1));*/
tvRating1.setText(priceList.getRating());
tvPrice1.setText(priceList.getPrice());
tvMPG1.setText(priceList.getMPG());
tvYear1.setText(priceList.getYear());
tvDisplayName.setText(priceList.getDisplayNames().get(position));
// Iterator myVeryOwnIterator = catList.getMapMpg().keySet().iterator();
/*while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
ArrayList<String> value=catList.getMapMpg().get(key);
//Toast.makeText(this, "Key: "+key+" Value: "+value.get(0)+" and "+value.get(1), Toast.LENGTH_LONG).show();
System.out.println("Key:"+key+" Value:"+value.get(0)+" and "+value.get(1));
}*/
//tvBrandName.setText(brandList.getDisplayNames().get(position));
imageLoader.displayImage(priceList.getImages().get(position), activity, productImage);
return vi;
}
// expose this method so that SearchResultActivity.onDestroy() can safely close the Thread.
public void stopImageLoader() {
if(imageLoader != null) {
imageLoader.stopThread();
}
}
}
ImageLoader.java:
package com.TCC.android.adapters;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import com.TCC.android.R;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = new ConcurrentHashMap<ImageView, String>();
public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
fileCache=new FileCache(context);
}
final int stub_id=R.drawable.ic_launcher;
public void displayImage(String url, Activity activity, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
InputStream is;
//from SD cache
Bitmap bitmap=null;
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
System.out.println("---------------------IMAGE URL: "+url);
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
return bitmap;
} catch (Exception ex){
System.out.println("---------------------IMAGE URL: "+url);
ex.printStackTrace();
return null;
}
finally{
bitmap = null;
is=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;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
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;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch(OutOfMemoryError e)
{
e.printStackTrace();
}catch (FileNotFoundException e) {}
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;
}
}
PhotosQueue photosQueue=new PhotosQueue();
public void stopThread()
{
photoLoaderThread.interrupt();
}
//stores list of photos to download
class PhotosQueue
{
private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
//removes all instances of this ImageView
public void Clean(ImageView image)
{
for(int j=0 ;j<photosToLoad.size();){
if(photosToLoad.get(j).imageView==image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while(true)
{
//thread waits until there are any images to load in the queue
if(photosQueue.photosToLoad.size()==0)
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.wait();
}
if(photosQueue.photosToLoad.size()!=0)
{
PhotoToLoad photoToLoad;
synchronized(photosQueue.photosToLoad){
photoToLoad=photosQueue.photosToLoad.pop();
}
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
String tag=imageViews.get(photoToLoad.imageView);
if(tag!=null && tag.equals(photoToLoad.url)){
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if(Thread.interrupted())
break;
}
} catch (InterruptedException e) {
//allow thread to exit
System.out.println("This is the Exit Point............");
}
}
}
PhotosLoader photoLoaderThread=new PhotosLoader();
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
public void run()
{
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}