我正在尝试获取用手机拍摄的照片的 URI。我正在尝试将传递给“onActivityResult”的数据转换为 URI,然后将此 URI 转换为字符串以存储在我的数据库中。这种方法确实适用于视频,那么如何用照片来实现呢?尝试将数据转换为 URI 时出现空指针异常。我应该使用不同的函数将照片数据转换为 URI 吗?我的代码如下:
按钮意图启动录像机:
recordVideoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startVideoFunction = new Intent();
startVideoFunction.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(startVideoFunction, REQUEST_CODE_VIDEO);
}
});
按钮意图开始照片捕捉:
takePhotosButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startPhotoFunction = new Intent();
startPhotoFunction.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(startPhotoFunction, REQUEST_CODE_PHOTO);
}
});
onActivityResult 方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case REQUEST_CODE_VIDEO:
videoUri = data.getData();
String videoPath = videoUri.toString();
videoDB.addVideoRow(videoPath);
//displayVideo.setVideoURI(videoUri);
//displayVideo.start();
break;
case REQUEST_CODE_PHOTO:
photoUri = data.getData();
String photoPath = photoUri.toString();
videoDB.addPhotoRow(photoPath);
break;
}
}catch (NullPointerException e){
//prevent crash when returning with Null data to mainactivity.
}
}
更新 onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
// try {
switch (requestCode) {
case REQUEST_CODE_VIDEO:
videoUri = data.getData();
String videoPath = videoUri.toString();
videoDB.addVideoRow(videoPath);
//displayVideo.setVideoURI(videoUri);
//displayVideo.start();
break;
case REQUEST_CODE_PHOTO:
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalFile = new File(getRealPathFromURI(tempUri));
String photoPath = finalFile.toString();
videoDB.addPhotoRow(photoPath);
break;
}
//}catch (NullPointerException e){
//prevent crash when returning with Null data to mainactivity.
//}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}