热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

图像内存错误-OutOfMemoryErrorwithimages

iamdisplayingimagesinlistviewandgettingoutofmemoryerroranyoneguidemewhatisthesolu

i am displaying images in listview and getting out of memory error any one guide me what is the solution to this problem here is my code

我在listview中显示图像,并得到内存错误任何一个都可以指导我解决这个问题的方法是我的代码

LogCat

LogCat

ERROR/AndroidRuntime(1010): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
ERROR/AndroidRuntime(1010):     at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
ERROR/AndroidRuntime(1010):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:405)
ERROR/AndroidRuntime(1010):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:418)
ERROR/AndroidRuntime(1010):     at com.Adapters.AdapterTours.getView(AdapterTours.java:73)
ERROR/AndroidRuntime(1010):     at android.widget.AbsListView.obtainView(AbsListView.java:1409)
ERROR/AndroidRuntime(1010):     at android.widget.ListView.makeAndAddView(ListView.java:1745)
ERROR/AndroidRuntime(1010):     at android.widget.ListView.fillUp(ListView.java:700)
ERROR/AndroidRuntime(1010):     at android.widget.ListView.fillGap(ListView.java:646)
ERROR/AndroidRuntime(1010):     at android.widget.AbsListView.trackMotionScroll(AbsListView.java:3399)
ERROR/AndroidRuntime(1010):     at android.widget.AbsListView.onTouchEvent(AbsListView.java:2233)
ERROR/AndroidRuntime(1010):     at android.widget.ListView.onTouchEvent(ListView.java:3446)
ERROR/AndroidRuntime(1010):     at android.view.View.dispatchTouchEvent(View.java:3885)
ERROR/AndroidRuntime(1010):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
ERROR/AndroidRuntime(1010):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
ERROR/AndroidRuntime(1010):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
ERROR/AndroidRuntime(1010):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
ERROR/AndroidRuntime(1010):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
ERROR/AndroidRuntime(1010):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1691)
ERROR/AndroidRuntime(1010):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1125)
ERROR/AndroidRuntime(1010):     at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
ERROR/AndroidRuntime(1010):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1675)
ERROR/AndroidRuntime(1010):     at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
ERROR/AndroidRuntime(1010):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
ERROR/AndroidRuntime(1010):     at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(1010):     at android.os.Looper.loop(Looper.java:130)
ERROR/AndroidRuntime(1010):     at android.app.ActivityThread.main(ActivityThread.java:3683)
ERROR/AndroidRuntime(1010):     at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(1010):     at java.lang.reflect.Method.invoke(Method.java:507)
ERROR/AndroidRuntime(1010):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
ERROR/AndroidRuntime(1010):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
ERROR/AndroidRuntime(1010):     at dalvik.system.NativeStart.main(Native Method)

GetView Method

GetView方法

public View getView(final int position, View convertView, ViewGroup parent) {

      ViewHolder holder;

      if (cOnvertView== null) {
        cOnvertView= mInflater.inflate(R.layout.list_tours, null);
        holder = new ViewHolder();
        holder.tourTitle = (TextView) convertView.findViewById(R.id.tourTitle);
        holder.tourIcon = (ImageView) convertView.findViewById(R.id.tourIcon);
        holder.tourDetail = (TextView) convertView.findViewById(R.id.tourDetail);
        convertView.setTag(holder);

      } else {
        holder = (ViewHolder) convertView.getTag();
      }


      DalTours tour = getItem(position);

        String tempTag = String.valueOf(tour.getId());
        holder.tourIcon.setTag(tempTag);

        if(tour.getImageByteArray() != null)
        {
            Bitmap image = BitmapFactory.decodeByteArray(tour.getImageByteArray(), 0, tour.getImageByteArray().length);
            holder.tourIcon.setImageDrawable(getScaledImage(image));
            image = null;

        }else
        {


            holder.tourIcon.setTag(tour);
            Bitmap cachedImage = ImageLoader.loadBitmap(tour,new ImageLoader.ImageCallback() {

                @Override
                public void imageLoaded(Bitmap imageBitmap, DalTours tour) {
                    ImageView image = (ImageView)listview.findViewWithTag(tour);
                     if(image != null)
                      {

                      try
                      {  
                          ByteArrayOutputStream stream = new ByteArrayOutputStream();
                          if(imageBitmap != null)
                          {


                              image.setImageDrawable(getScaledImage(imageBitmap));
                              imageBitmap.compress(CompressFormat.PNG, 0 ,stream);
                              byte[] bitmapdata = stream.toByteArray();
                              tours.get(position).setImageByteArray(bitmapdata);


                         }
                          stream = null;
                      }finally
                      {

                      }
                      }

                }
            });
              holder.tourIcon.setImageDrawable(getScaledImage(cachedImage));

        }

      holder.tourTitle.setText(tours.get(position).getTitle());
      holder.tourDetail.setText(tours.get(position).getDetail());

      return convertView;
    }

image Scale Function

图像比例尺功能

 public Drawable getScaledImage(Bitmap actualBitmap)
    {
        BitmapDrawable bmd= null;
        if(actualBitmap != null)
        {

            int width = actualBitmap.getWidth();
            int height = actualBitmap.getHeight();

            Activity parent = (Activity)context;
            Display display = parent.getWindowManager().getDefaultDisplay(); 
            int Screenwidth = display.getWidth();
            int Screenheight = display.getHeight();


         float newWidth = (Screenwidth*35)/100;

         float temp = newWidth / width;
         float newHeight =  temp * height;



        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(actualBitmap, 0, 0, 
                          width, height, matrix, true); 

        bmd = new BitmapDrawable(resizedBitmap);
        }
        return bmd;

    }

Image Loader Class

图像加载器类

public  class ImageLoader {
    private static HashMap> imageCache;

    public ImageLoader() {
        //imageCache = new HashMap>();
    }

    public static Bitmap loadBitmap(final DalTours tour, final ImageCallback imageCallback) {
        if(imageCache == null)
            imageCache = new HashMap>();

        if (imageCache.containsKey(tour.getImageurl())) {
            SoftReference softReference = imageCache.get(tour.getImageurl());
            Bitmap Bitmap = softReference.get();
            if (Bitmap != null) {
                return Bitmap;
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageCallback.imageLoaded((Bitmap) message.obj, tour);
            }
        };
        new Thread() {
            @Override
            public void run() {
                Bitmap Bitmap = loadImageFromUrl(tour.getImageurl());
                imageCache.put(tour.getImageurl(), new SoftReference(Bitmap));
                Message message = handler.obtainMessage(0, Bitmap);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }

    public static Bitmap loadImageFromUrl(String url) {

        Bitmap bm;
        try {  

                URL aURL = new URL(url);  
                URLConnection cOnn= aURL.openConnection(); 

                conn.connect();  
                InputStream is = null;
                try
                {
                 is= conn.getInputStream();  
                }catch(IOException e)
                {
                     return null;
                }

                BufferedInputStream bis = new BufferedInputStream(is);  

                bm = BitmapFactory.decodeStream(bis);  
                bis.close();  
                is.close();  

           } catch (IOException e) {  
            return null;
           }  

           return  bm;


    }

    public interface ImageCallback {
        public void imageLoaded(Bitmap imageBitmap, DalTours tour);
    }
}

any help would be apprecicated

任何帮助都是值得感激的

4 个解决方案

#1


25  

For Solving java.lang.OutOfMemoryError Exception at android.graphics.BitmapFactory.nativeDecodeByteArray, you should use Following Code:

求解. lang。在android.graphics.BitmapFactory OutOfMemoryError异常。nativedecoytearray,应该使用以下代码:

BitmapFactory.Options optiOns=new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
                options.inPurgeable = true; // inPurgeable is used to free up memory while required
                Bitmap songImage1 = BitmapFactory.decodeByteArray(thumbnail,0, thumbnail.length,options);//Decode image, "thumbnail" is the object of image file
                Bitmap sOngImage= Bitmap.createScaledBitmap(songImage1, 50 , 50 , true);// convert decoded bitmap into well scalled Bitmap format.

imageview.SetImageDrawable(songImage);

#2


6  

finally i solve this high resolution image issue which was causing out of memory error using following thread Large Image Manipulation

最后,我解决了这个高分辨率的图像问题,这是由于使用以下线程的大图像处理导致内存错误。

and here is my code for downloading and scaling image according to your required size.

这是我下载和缩放图像的代码,根据你需要的大小。

no more custom scaling function required!!!

不再需要自定义缩放功能!!

public static Bitmap loadImageFromUrl(String url) {

        Bitmap bm;
        try {  

                URL aURL = new URL(url);  
                URLConnection cOnn= aURL.openConnection(); 

                conn.connect();  
                InputStream is = null;
                try
                {
                 is= conn.getInputStream();  
                }catch(IOException e)
                {
                     return null;
                }

                BufferedInputStream bis = new BufferedInputStream(is);  

                bm = BitmapFactory.decodeStream(bis);

                bis.close();  
                is.close();  

           } catch (IOException e) {  
            return null;
           }  

        return  Bitmap.createScaledBitmap(bm,100,100,true);


    }

#3


3  

you have to recycle bitmap. The bitmap implementation is native, so the java object is small and a poor candidate for java garbage collection but the memory is still allocated. Taka a look to Bitmap.recycle()

你必须回收位图。位图实现是本地的,所以java对象很小,不适合java垃圾收集,但是内存仍然被分配。查看bitmap . recycling ()

#4


-1  

It is definitely a case of having a bitmap for a large image in the memory. If you are repeatedly doing this operation then its good to recycle the bitmap every time. However, just recycling does not guarantee that the memory is freed, its barely marked for garbage collection. So, as an additional step, you should take care of garbage collection too.

这绝对是一个在内存中有一个大图像的位图的例子。如果您反复做这个操作,那么每次都可以回收位图。然而,仅仅是回收并不保证释放内存,它几乎没有标记为垃圾收集。因此,作为一个附加步骤,您也应该处理垃圾收集。

Use this code;

使用这段代码;

Bitmap mybitmap = ....; // you are getting the bitmap here
mybitmap.recycle();
System.gc(); // the above recycling may not be enough always

推荐阅读
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • 本文详细介绍了Android中的坐标系以及与View相关的方法。首先介绍了Android坐标系和视图坐标系的概念,并通过图示进行了解释。接着提到了View的大小可以超过手机屏幕,并且只有在手机屏幕内才能看到。最后,作者表示将在后续文章中继续探讨与View相关的内容。 ... [详细]
  • php缓存ri,浅析ThinkPHP缓存之快速缓存(F方法)和动态缓存(S方法)(日常整理)
    thinkPHP的F方法只能用于缓存简单数据类型,不支持有效期和缓存对象。S()缓存方法支持有效期,又称动态缓存方法。本文是小编日常整理有关thinkp ... [详细]
  • 本文整理了Java中org.gwtbootstrap3.client.ui.Icon.addDomHandler()方法的一些代码示例,展示了Icon.ad ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 纠正网上的错误:自定义一个类叫java.lang.System/String的方法
    本文纠正了网上关于自定义一个类叫java.lang.System/String的错误答案,并详细解释了为什么这种方法是错误的。作者指出,虽然双亲委托机制确实可以阻止自定义的System类被加载,但通过自定义一个特殊的类加载器,可以绕过双亲委托机制,达到自定义System类的目的。作者呼吁读者对网上的内容持怀疑态度,并带着问题来阅读文章。 ... [详细]
  • 本文介绍了在C#中SByte类型的GetHashCode方法,该方法用于获取当前SByte实例的HashCode。给出了该方法的语法和返回值,并提供了一个示例程序演示了该方法的使用。 ... [详细]
author-avatar
你不懂_de_笑
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有