【发布时间】:2019-07-18 14:25:57
【问题描述】:
我正在关注this 博客文章,以将此功能添加到我的应用程序中,我可以在其中拍照,然后将图片数据保存为 Uri 以使用更多功能。但是当我尝试打开相机意图时出现错误。
java.lang.NullPointerException:尝试在 null 上调用虚拟方法 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)'对象引用
我怀疑file_paths.xml 有问题,但我仔细检查了没有问题。我已经对通过FileProvider 等保存图像的不同方式进行了一些研究,但其中大部分对我也不起作用。
有人知道我的代码有什么问题吗?
MainActivity
private void openCameraIntent() {
Intent pictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if(pictureIntent.resolveActivity(getPackageManager()) != null){
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, com.example.camerapplication.provider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
photoURI);
startActivityForResult(pictureIntent,
REQUEST_CAPTURE_IMAGE);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK){
Glide.with(this).load(imageFilePath).into(image);
// TODO:Use Image Uri for further functions
}
}
private File createImageFile() throws IOException{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName,".jpg",storageDir);
imageFilePath = image.getAbsolutePath();
return image;
}
清单
<uses-feature android:name="android.hardware.camera" android:required="true" />
// ... Other elements and then
// Within application scope
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.cameraapplication/files/Pictures" />
</paths>
已编辑 更改为正确的路径="Android/data/com.example.cameraapplication/files/Pictures"
【问题讨论】:
标签: java android nullpointerexception android-camera