問題描述:
選擇相簿或者拍照的圖片,然後綁定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 @Override11 public void setViewImage(ImageView imageView, String imageFile) {12 13 // TODO Auto-generated method stub14 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,因為之前我們將其設定成了true24 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(Math60 .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 }