Android从asmx Web服务加载图像时触发OutOfMemoryError

时间:2015-02-16 07:24:28

标签: android web-services android-listview android-studio asmx

导致此错误的原因是什么:      java.lang.OutOfMemoryError:无法分配带有1305618个空闲字节的10111384字节分配和1275KB直到OOM

此行发生错误:

Bitmap bmp = BitmapFactory.decodeByteArray(currentTour.getTourImage(),0,currentTour.getTourImage().length);

我的ListView适配器查看:

  public View getView(int position, View view, ViewGroup parent) {

        if (view == null)
            view = getLayoutInflater().inflate(R.layout.tour_item, parent, false);
        if (position % 2 == 1) {
            view.setBackgroundColor(Color.rgb(189, 230, 247));
        } else {
            view.setBackgroundColor(Color.WHITE);
        }


        TourAnounceRow currentTour = tourAnounceList.get(position);

        if (currentTour != null) {
            TextView tourName = (TextView) view.findViewById(R.id.lblTourName);
            tourName.setText(currentTour.getTourName());

            TextView place = (TextView) view.findViewById(R.id.lblPlace);
            place.setText(currentTour.getPlace());

            RatingBar tourStarCount = (RatingBar) view.findViewById(R.id.ratingBarTourStarCount);
            tourStarCount.setRating(Float.parseFloat(String.valueOf(currentTour.getHotelStarsCount())));

            TextView adultCount = (TextView) view.findViewById(R.id.lblAdultCount);
            adultCount.setText(String.valueOf(currentTour.getAdultCount()));

            TextView childrenCount = (TextView) view.findViewById(R.id.lblChildCount);
            childrenCount.setText(String.valueOf(currentTour.getChildrenCount()));
            TextView mealCount = (TextView) view.findViewById(R.id.lblMealCount);
            mealCount.setText(String.valueOf(currentTour.getDailyMealCount()));

            TextView price = (TextView) view.findViewById(R.id.lblPrice);
            price.setText(String.valueOf(currentTour.getPrice()));

            ImageView ivTourImage = (ImageView) view.findViewById(R.id.ivTourImage);
            ivTourImage.setScaleType(ImageView.ScaleType.FIT_XY);


            Bitmap bmp = BitmapFactory.decodeByteArray(currentTour.getTourImage(), 0,currentTour.getTourImage().length);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.WEBP, 10, stream);


            ivTourImage.setImageBitmap(bmp);

        }
        return view;
    }

2 个答案:

答案 0 :(得分:1)

这是因为你的位图很大,你可以优化位图的负载,看看this link

答案 1 :(得分:1)

我建议,特别是因为你在ListView中使用它,你可以看一下Glide Library(https://github.com/bumptech/glide)。该库将处理加载图像的异步调用,以及调整图像大小以适合您的ImageView(保存内存)。

你似乎也在内存中保存了很多byte []图像(基于tourAnounceList),你想在可能的情况下只保留对它们的引用;或者作为URL / URI或本地资源整数(R.drawable.my_image)。

代码应如下所示:

ImageView ivTourImage = (ImageView) view.findViewById(R.id.ivTourImage);
Glide.with(parent.getContext()).load(currentTour.getImageUrl())
    .fitCenter().into(ivTourImage);