在Gridview中加载图像时出现OutofMemory错误

时间:2016-02-08 07:10:45

标签: android

当我遇到adapter的问题时,我在我的OutofMemory Error中实现了以下代码。但问题是我只能加载第一个输入代码这里是第0个图像gridview中的位置。以下是我的代码,请建议更改。

public class GridAdapter extends BaseAdapter {

    String[] names;
    int[] images;
    Context context;
    private static LayoutInflater inflater=null;

    //private LruCache<String bitmap="",> memorucache;
    private LruCache<String, Bitmap> mMemoryCache;


    public  GridAdapter(Context mainActivity,String[] _names,int[] _images){

        names=_names;
        images=_images;
        context=mainActivity;
        inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final int maxMemory= (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize=maxMemory/8;

        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };

    }

    @Override
    public int getCount() {
        return names.length;
    }

    @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) {

        Holder holder=new Holder();
        View rowView;

        rowView=inflater.inflate(R.layout.gridlist,null);
        holder.txtview= (TextView) rowView.findViewById(R.id.textView1);
        holder.imageview= (ImageView) rowView.findViewById(R.id.imageView1);

        holder.txtview.setText(names[position]);
        loadBitmap(images[position], holder.imageview);
        //holder.imageview.setImageResource(images[position]);
        //rowView.setBackgroundColor(Color.parseColor(getColorCode()));

        return rowView;
    }

    private void loadBitmap(int image, ImageView mimageview) {

        final String imagekey=String.valueOf(image);

        final Bitmap bitmap=getBitmapFromMemCache(imagekey);

        if(bitmap != null){

            mimageview.setImageBitmap(bitmap);
        }else{
            mimageview.setImageResource(R.drawable.ic_launcher);
            final BitmapWorkerTask task=new BitmapWorkerTask(mimageview);
            task.execute(image);
        }


    }

    public class Holder{

        TextView txtview;
        ImageView imageview;

    }
    public String getColorCode(){
        String[] colors = {"#6600CC","#3399FF","#FF9900","#003399","#CC6600"
                ,"#336600","#339933","#009999","#99CC00","#666633"
                ,"#666699","#333399","#003399","#993399","#990033"};

        int random = (int)(Math.random()*14+1);
        return colors[random];
    }

    class  BitmapWorkerTask extends AsyncTask<Integer,Void,Bitmap>{

        private final WeakReference<ImageView> imageViewReference;
        public BitmapWorkerTask(ImageView mimageview) {

            imageViewReference = new WeakReference<ImageView>(mimageview);;
        }

        @Override
        protected Bitmap doInBackground(Integer... params) {

            final Bitmap bitmap = decodeSampledBitmapFromResource(
                    context.getResources(), params[0], 100, 100);

            addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
            return bitmap;

            //return null;
        }
    }

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res,
                                                         int resId, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }


    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio;

        }
        return inSampleSize;
    }


}

4 个答案:

答案 0 :(得分:0)

请在您的Manifest应用程序代码中添加此内容。

 android:largeHeap="true"

修改

ImageLoader

imageLoader.loadImage(imageUri, new SimpleImageLoadingListener()  
{ 
    @Override 
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) 
    { 
         // Do whatever you want with Bitmap 
    } 
}); 

答案 1 :(得分:0)

您的图像太大,无法加载到内存中。执行以下步骤:

希望这有帮助。

答案 2 :(得分:0)

您可以尝试使用通用图片加载器(https://github.com/nostra13/Android-Universal-Image-Loader)或 Picasso http://square.github.io/picasso/),我认为这种方式更简单。

但如果您不想使用库,那么您应该添加行

机器人:largeHeap = “真”

到您的清单。

答案 3 :(得分:0)

试试这个

public Bitmap resizedBitmap(Bitmap originalImage, int width, int height) {
    Bitmap background = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
    float originalWidth = originalImage.getWidth(), originalHeight = originalImage.getHeight();
    Canvas canvas = new Canvas(background);
    float scale = width / originalWidth;
    float xTranslation = 0.0f, yTranslation = (height - originalHeight * scale) / 2.0f;
    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);
    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(originalImage, transformation, paint);
    return background;
}

添加了滤镜。