问题
I'm trying to take a photo in my device's camera, when I call the method that handles the image capture the app crashes because of a nullpointer exception. I don't know what information is missing with my FileProvider as the stacktrace points the nullpointer into my FileProvider.getUriForFile statement.
Here's my code HomeActivity
public void takePhoto(View view){
//camera stuff
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "AnimEncylopedia");
if(!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = FileProvider.getUriForFile(HomeActivity.this, "com.encyclopedia.fileprovider", image);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 1);
}
AndroidManifest
<provider
android:authorities="com.encyclopedia.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
Files_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Encyclopedia/"/>
</paths>
How can I fix this?
回答1:
Use camera intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
in onActivityResult()
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri tempUri = getImageUri(getActivity(), photo);
It also depends on the camera app the user is using. With android camera it will work fine. But for other apps it depends whether they return a valid value for data or not.
来源:https://stackoverflow.com/questions/40814463/fileprovider-geturiforfile-returns-null