Android 在ListView中使用LazyList时出现内存不足错误

Android 在ListView中使用LazyList时出现内存不足错误,android,android-listview,lazy-loading,android-adapter,lazylist,Android,Android Listview,Lazy Loading,Android Adapter,Lazylist,可能重复: 我一直在遵循关于在列表视图中延迟加载图像的教程,并且比我实现的要慢。代码按照我的要求正常工作,但在某些阶段会出现内存不足错误。我正在使用与ImageLoader、内存缓存、LazyAdapter、FileChache和UTIL相同的代码。 这是LazyAdapter类 public class LazyAdapter extends BaseAdapter { private Activity activity; private ArrayList<Stri

可能重复:

我一直在遵循关于在列表视图中延迟加载图像的教程,并且比我实现的要慢。代码按照我的要求正常工作,但在某些阶段会出现内存不足错误。我正在使用与ImageLoader、内存缓存、LazyAdapter、FileChache和UTIL相同的代码。 这是LazyAdapter类

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<String> movieThumbnail;
    private ArrayList<String> movieText;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 

    public LazyAdapter(Activity a, ArrayList<String> movieThumbnail, ArrayList<String> movieText) {
        activity = a;
        /*data=d;*/
        this.movieThumbnail = movieThumbnail;
        this.movieText = movieText;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return movieText.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.listrow, null);

        TextView text=(TextView)vi.findViewById(R.id.rowListTextView);
        ImageView image=(ImageView)vi.findViewById(R.id.movieImage);
        text.setText(movieText.get(position));
        imageLoader.DisplayImage(movieThumbnail.get(position), image);
        return vi;
    }
}
公共类LazyAdapter扩展了BaseAdapter{
私人活动;
私家侦探片;
私人编剧电影文本;
专用静态充气机=空;
公共图像加载器;
公共懒散适配器(活动a,ArrayList MovietHumbail,ArrayList MovietText){
活动=a;
/*数据=d*/
this.movieThumbnail=movieThumbnail;
this.movieText=movieText;
充气器=(LayoutInflater)activity.getSystemService(Context.LAYOUT\u充气器\u SERVICE);
imageLoader=新的imageLoader(activity.getApplicationContext());
}
public int getCount(){
返回movieText.size();
}
公共对象getItem(int位置){
返回位置;
}
公共长getItemId(int位置){
返回位置;
}
公共视图getView(int位置、视图转换视图、视图组父视图){
视图vi=转换视图;
if(convertView==null)
vi=充气机充气(R.layout.listrow,空);
TextView text=(TextView)vi.findViewById(R.id.rowListTextView);
ImageView image=(ImageView)vi.findViewById(R.id.movieImage);
text.setText(movieText.get(position));
imageLoader.DisplayImage(movieThumbnail.get(位置)、image);
返回vi;
}
}
记忆卡

public class MemoryCache {

    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes

    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/6);
    }

    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;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            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){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            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{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }

    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}
公共类内存缓存{
私有静态最终字符串TAG=“MemoryCache”;
私有映射缓存=Collections.synchronizedMap(
新LinkedHashMap(10,1.5f,true));//LRU排序的最后一个参数true
私有长大小=0;//当前分配的大小
private long limit=1000000;//最大内存(字节)
公共内存缓存(){
//使用可用堆大小的25%
setLimit(Runtime.getRuntime().maxMemory()/6);
}
公共无效设置限制(长新限制){
限制=新的限制;
Log.i(标记“MemoryCache将使用最多”+限制/1024./1024.+“MB”);
}
公共位图获取(字符串id){
试一试{
如果(!cache.containsKey(id))
返回null;
//NullPointerException有时发生在这里http://code.google.com/p/osmdroid/issues/detail?id=78 
返回cache.get(id);
}捕获(NullPointerException ex){
例如printStackTrace();
返回null;
}
}
公共void put(字符串id、位图){
试一试{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id,位图);
size+=getSizeInBytes(位图);
checkSize();
}捕获(可丢弃){
th.printStackTrace();
}
}
私有void checkSize(){
Log.i(标记“cache size=“+size+”length=“+cache.size());
如果(大小>限制){
迭代器iter=cache.entrySet().Iterator();//最近访问最少的项将是第一个迭代的项
while(iter.hasNext()){
Entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();

如果(size使用此方法加载图像,则在使用滚动而非强制关闭时不会产生问题

    MainClassActivity:
ArrayList<NewsItems> news = new ArrayList<NewsItems>();
    SetListView sta;
       sta = new SetListView(MainActivity.this, news);
                    lv.setAdapter(sta);

                    for (NewsItems s : news) {
                            s.loadImage(sta);
                    }


        public class SetListView  extends BaseAdapter{
            private LayoutInflater inflater = null;
            Activity activity;
            ArrayList<NewsItems> one;
            public SetListView(Activity a,ArrayList<NewsItems> one)
            {
                this.activity = a;
                inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                this.one = one;
            }

            @Override
            public int getCount() {
                return one.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View vi = convertView;
                if (convertView == null)
                    vi = inflater.inflate(R.layout.main1, null);
                TextView tv1 = (TextView) vi.findViewById(R.id.textView1);
                TextView tv2 = (TextView) vi.findViewById(R.id.textView2);
                tv1.setText(one.get(position).get_title());
                tv2.setText(one.get(position).get_pudDate());
        //      Bitmap bm = loadBitmap(one.get(position).get_image());
                if(one.get(position).get_bm() != null)
                    ((ImageView)vi.findViewById(R.id.imageView1)).setImageBitmap(one.get(position).get_bm());
                else
                    ((ImageView)vi.findViewById(R.id.imageView1)).setImageResource(R.drawable.ic_launcher);
                return vi;
            }

        }


package com.dudhat.classes;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.dudhat.rssfeeds.SetListView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

public class NewsItems {
    private SetListView sta;
    String _title,_pudDate,_description,_image;
    Bitmap _bm;

    public Bitmap get_bm() {
        return _bm;
    }

    public String get_image() {
        return _image;
    }

    public String get_title() {
        return _title;
    }

    public String get_pudDate() {
        return _pudDate;
    }

    public String get_description() {
        return _description;
    }
    public SetListView getAdapter() {
        return sta;
    }

    public void setAdapter(SetListView sta) {
        this.sta = sta;
    }
    public NewsItems(String _title,String _pubdate,String _description,String _image,Bitmap _bm)
    {
        this._description = _description;
        this._pudDate = _pubdate;
        this._title = _title;
        this._image = _image;
        this._bm = _bm;
    }
     public void loadImage(SetListView sta) {
                 this.sta = sta;
                 if (_image != null && !_image.equals("")) {
                        new ImageLoadTask().execute(_image);
              }
             }
    private class ImageLoadTask extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            Log.i("ImageLoadTask", "Loading image...");
        }

        protected Bitmap doInBackground(String... param) {
            Log.i("ImageLoadTask", "Attempting to load image URL: " + param[0]);
            try {
                Bitmap b = loadBitmap(param[0]);
                return b;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        protected void onPostExecute(Bitmap ret) {
            if (ret != null) {
                _bm = ret;
                if (sta != null) {
                    sta.notifyDataSetChanged();
                }
            } else {
            }
        }
    }
    public Bitmap loadBitmap(String url)
    {
        Bitmap bm = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try 
        {
            URLConnection conn = new URL(url).openConnection();
            conn.connect();
            is = conn.getInputStream();
            bis = new BufferedInputStream(is, 8192);
            bm = BitmapFactory.decodeStream(bis);
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        finally {
            if (bis != null) 
            {
                try 
                {
                    bis.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
            if (is != null) 
            {
                try 
                {
                    is.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
        return bm;
    }
}
MainClassActivity:
ArrayList news=新的ArrayList();
SetListView sta;
sta=新的SetListView(MainActivity.this,news);
低压设置适配器(sta);
用于(新闻项目s:新闻){
s、 loadImage(sta);
}
公共类SetListView扩展了BaseAdapter{
专用充气机=空;
活动;
ArrayList 1;
公共SetListView(活动a,ArrayList one)
{
本活动=a;
充气器=(LayoutInflater)a.getSystemService(Context.LAYOUT\u充气器\u SERVICE);
这个1=1;
}
@凌驾
public int getCount(){
返回1.size();
}
@凌驾
公共对象getItem(int位置){
返回位置;
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图vi=转换视图;
if(convertView==null)
vi=充气机。充气(R.layout.main1,空);
TextView tv1=(TextView)vi.findViewById(R.id.textView1);
TextView tv2=(TextView)vi.findViewById(R.id.textView2);
tv1.setText(one.get(position.get_title());
tv2.setText(one.get(position.get_pudDate());
//位图bm=loadBitmap(one.get(position.get_image());
if(one.get(position.get_bm()!=null)
((ImageView)vi.findViewById(R.id.imageView1)).setImageBitmap(one.get(position.get_bm());
其他的
((ImageView)vi.findViewById(R.id.imageView1)).setImageResource(R.drawable.ic_启动器);
返回vi;
}
}
包com.dudhat.classes;
导入java.io.BufferedInputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.URL;
导入java.net.URLConnection;
导入com.dudhat.rssfeeds.SetListView;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.os.AsyncTask;
导入android.util.Log;
公共类新闻项目{
私有集合列表vi
    MainClassActivity:
ArrayList<NewsItems> news = new ArrayList<NewsItems>();
    SetListView sta;
       sta = new SetListView(MainActivity.this, news);
                    lv.setAdapter(sta);

                    for (NewsItems s : news) {
                            s.loadImage(sta);
                    }


        public class SetListView  extends BaseAdapter{
            private LayoutInflater inflater = null;
            Activity activity;
            ArrayList<NewsItems> one;
            public SetListView(Activity a,ArrayList<NewsItems> one)
            {
                this.activity = a;
                inflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                this.one = one;
            }

            @Override
            public int getCount() {
                return one.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View vi = convertView;
                if (convertView == null)
                    vi = inflater.inflate(R.layout.main1, null);
                TextView tv1 = (TextView) vi.findViewById(R.id.textView1);
                TextView tv2 = (TextView) vi.findViewById(R.id.textView2);
                tv1.setText(one.get(position).get_title());
                tv2.setText(one.get(position).get_pudDate());
        //      Bitmap bm = loadBitmap(one.get(position).get_image());
                if(one.get(position).get_bm() != null)
                    ((ImageView)vi.findViewById(R.id.imageView1)).setImageBitmap(one.get(position).get_bm());
                else
                    ((ImageView)vi.findViewById(R.id.imageView1)).setImageResource(R.drawable.ic_launcher);
                return vi;
            }

        }


package com.dudhat.classes;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.dudhat.rssfeeds.SetListView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

public class NewsItems {
    private SetListView sta;
    String _title,_pudDate,_description,_image;
    Bitmap _bm;

    public Bitmap get_bm() {
        return _bm;
    }

    public String get_image() {
        return _image;
    }

    public String get_title() {
        return _title;
    }

    public String get_pudDate() {
        return _pudDate;
    }

    public String get_description() {
        return _description;
    }
    public SetListView getAdapter() {
        return sta;
    }

    public void setAdapter(SetListView sta) {
        this.sta = sta;
    }
    public NewsItems(String _title,String _pubdate,String _description,String _image,Bitmap _bm)
    {
        this._description = _description;
        this._pudDate = _pubdate;
        this._title = _title;
        this._image = _image;
        this._bm = _bm;
    }
     public void loadImage(SetListView sta) {
                 this.sta = sta;
                 if (_image != null && !_image.equals("")) {
                        new ImageLoadTask().execute(_image);
              }
             }
    private class ImageLoadTask extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            Log.i("ImageLoadTask", "Loading image...");
        }

        protected Bitmap doInBackground(String... param) {
            Log.i("ImageLoadTask", "Attempting to load image URL: " + param[0]);
            try {
                Bitmap b = loadBitmap(param[0]);
                return b;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        protected void onPostExecute(Bitmap ret) {
            if (ret != null) {
                _bm = ret;
                if (sta != null) {
                    sta.notifyDataSetChanged();
                }
            } else {
            }
        }
    }
    public Bitmap loadBitmap(String url)
    {
        Bitmap bm = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try 
        {
            URLConnection conn = new URL(url).openConnection();
            conn.connect();
            is = conn.getInputStream();
            bis = new BufferedInputStream(is, 8192);
            bm = BitmapFactory.decodeStream(bis);
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        finally {
            if (bis != null) 
            {
                try 
                {
                    bis.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
            if (is != null) 
            {
                try 
                {
                    is.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
        return bm;
    }
}