簡體   English   中英

Android從Asmx Web服務加載圖像時觸發OutOfMemoryError

[英]Android fires OutOfMemoryError while loading image from asmx web service

可能導致此錯誤的原因:java.lang.OutOfMemoryError:未能分配10111384字節分配和1305618可用字節和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;
    }

發生這種情況是因為您的位圖過大,您可以優化位圖的負載,請查看此鏈接

我建議,尤其是因為您在ListView中使用了它,因此您應該看一下Glide庫( 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM