FileProvider.getUriForFile returns null

廉价感情. 提交于 2019-12-02 08:38:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!