导语:
如今的安卓应用在选择图片的处理上大多合并使用拍照和从相册中选择这两种方式(当然这是产品dog的事,开篇跑题。。。)
今天在写一个这样的功能模块遇到一个尴尬的问题,同样是拍照获取图片功能,在同事的三星上跑没问题,但是在我的手机上一跑就崩(吐槽一下国产厂商对android的系统级改造真是太大,连错误日志都打不出来,还有老板啥时候给我配个测试机呗),下面是在某型手机上测试的报错结果
错误报告:
10-21 17:41:43.634: E/AndroidRuntime(32683): FATAL EXCEPTION: main
10-21 17:41:43.634: E/AndroidRuntime(32683): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=-1, data=Intent { act=inline-data (has extras) }} to activity {*****}: java.lang.NullPointerException
问题分析:
这是出错部分代码,可以看到我直接从返回Intent中获取uri,但实际上有些手机在拍照后uri是空的,所以空指针异常也不奇怪了
if (resultCode == RESULT_OK) { Uri uri = data.getData(); ContentResolver cr = this.getContentResolver(); try { if (bmp != null) bmp.recycle(); bmp = BitmapFactory.decodeStream(cr.openInputStream(uri)); bmp = MediaStore.Images.Media.getBitmap(cr, uri); imagedata = StreamUtils.stream2ByteArray(cr .openInputStream(uri)); AVFile img_file = new AVFile("photo_1", imagedata); img_file.saveInBackground(); images.add(img_file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } photo.setImageBitmap(bmp); } else { Toast.makeText(PublishActivity.this, "请重新选择图片", Toast.LENGTH_SHORT).show(); }
所以解决方法就是分别处理从相册选取和拍照这两种情况,以便能适应更多的设备
解决办法
10代表拍照,20代表从相册选取。
if (requestCode == 10) { if (resultCode == RESULT_OK) { if (bmp != null) bmp.recycle(); bmp = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos); imagedata = baos.toByteArray(); AVFile img_file = new AVFile("photo_1", imagedata); img_file.saveInBackground(); images.add(img_file); photo.setImageBitmap(bmp); } else { Toast.makeText(PublishActivity.this, "请重新选择图片", Toast.LENGTH_SHORT).show(); } } if (requestCode == 20) { if (resultCode == RESULT_OK) { Uri uri = data.getData(); ContentResolver cr = this.getContentResolver(); try { if (bmp != null) bmp.recycle(); bmp = BitmapFactory.decodeStream(cr.openInputStream(uri)); bmp = MediaStore.Images.Media.getBitmap(cr, uri); imagedata = StreamUtils.stream2ByteArray(cr .openInputStream(uri)); AVFile img_file = new AVFile("photo_1", imagedata); img_file.saveInBackground(); images.add(img_file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } photo.setImageBitmap(bmp); } else { Toast.makeText(PublishActivity.this, "请重新选择图片", Toast.LENGTH_SHORT).show(); } }
时间: 2024-10-13 22:56:33