相机意图返回的Uri为空
我正在尝试创建一个Android应用程序,该程序可以拍摄照片或将照片上传到服务器.我的主要目的是获取意图返回的照片的URI.我遵循了[1]中的步骤. 问题在于,在装有Lollipop 5.1.1版的手机上可以正常工作,并且该意图返回照片的URI,但是在具有Jelly Bean 4.2.1版的手机上,该意图中返回的URI为空.
I am trying to create and Android application that takes a photo or uploads a photo to the server. My main objective is to get the URI of the photo which is returned in the intent. I have followed the steps from [1]. The problem is that on a phone with Lollipop, version 5.1.1 it works fine and the intent returns the URI of the photo, but on a phone which has Jelly Bean, version 4.2.1, the URI returned in the intent is null.
这是我的代码
创建视图并将侦听器设置为按钮
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_GET_PHOTO = 2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_page, container, false);
camera = (FloatingActionButton) view.findViewById(R.id.take_photo);
upload = (FloatingActionButton) view.findViewById(R.id.upload_photo);
photo = (ImageView) view.findViewById(R.id.photo);
camera.setOnClickListener(takePhoto);
upload.setOnClickListener(uploadPhoto);
return view;
}
拍摄照片
View.OnClickListener takePhoto = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
};
从图库监听器上传
View.OnClickListener uploadPhoto = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
if (photoPickerIntent.resolveActivity(getActivity().getPackageManager()) != null) {
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_GET_PHOTO);
}
}
};
处理意图结果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_GET_PHOTO)) {
Uri imageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), imageUri);
String filePath = getPath(imageUri);
bitmap = BitmapRotator.rotateBitmap(bitmap, filePath);
photo.setImageBitmap(bitmap);
UploadPhotoController.uploadPhoto(filePath);
} catch (IOException e) {
e.printStackTrace();
} catch (PhotoNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
data.getData()为null,因此我无法获取uri或图像的文件路径.
data.getData() is null thus I can't get the uri, or the file path of the image.
谢谢.
[1] http://developer.android.com/training/camera/photobasics .html
在StackOverflow上,您会根据自己的需要找到以下主题:
on StackOverflow you would find these topics according to yours: