问题描述:
选择相册或者拍照的图片,然后绑定GirdView,选择一张照片的时候,app运行正常,当选择多张照片时,app莫名的直接退出。
开始百思不得其解,经验告诉自己,去查看LogCat跟踪信息,结果发现很耀眼的词汇,
OutOfMemoryError,擦擦 果然是你导致的
解决方案:
1 public class MySimpleAdapter extends SimpleAdapter 2 { 3 public MySimpleAdapter(Context context, 4 List<? extends Map<String, ?>> data, int resource, String[] from, 5 int[] to) { 6 super(context, data, resource, from, to); 7 // TODO Auto-generated constructor stub 8 } 9 10 @Override 11 public void setViewImage(ImageView imageView, String imageFile) { 12 13 // TODO Auto-generated method stub 14 try { 15 imageView.setImageResource(Integer.parseInt(imageFile)); 16 } catch (NumberFormatException nfe) { 17 18 BitmapFactory.Options opts = new BitmapFactory.Options(); 19 opts.inJustDecodeBounds = true; 20 BitmapFactory.decodeFile(imageFile, opts); 21 22 opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128); 23 // 这里一定要将其设置回false,因为之前我们将其设置成了true 24 opts.inJustDecodeBounds = false; 25 try { 26 Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts); 27 imageView.setImageBitmap(bmp); 28 } catch (OutOfMemoryError err) { 29 } 30 } 31 // 32 33 } 34 35 36 public static int computeSampleSize(BitmapFactory.Options options, 37 int minSideLength, int maxNumOfPixels) { 38 int initialSize = computeInitialSampleSize(options, minSideLength, 39 maxNumOfPixels); 40 41 int roundedSize; 42 if (initialSize <= 8) { 43 roundedSize = 1; 44 while (roundedSize < initialSize) { 45 roundedSize <<= 1; 46 } 47 } else { 48 roundedSize = (initialSize + 7) / 8 * 8; 49 } 50 51 return roundedSize; 52 } 53 54 private static int computeInitialSampleSize(BitmapFactory.Options options, 55 int minSideLength, int maxNumOfPixels) { 56 double w = options.outWidth; 57 double h = options.outHeight; 58 59 int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math 60 .sqrt(w * h / maxNumOfPixels)); 61 int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( 62 Math.floor(w / minSideLength), Math.floor(h / minSideLength)); 63 64 if (upperBound < lowerBound) { 65 return lowerBound; 66 } 67 68 if ((maxNumOfPixels == -1) && (minSideLength == -1)) { 69 return 1; 70 } else if (minSideLength == -1) { 71 return lowerBound; 72 } else { 73 return upperBound; 74 } 75 } 76 77 }