Search code examples
javaandroid

Java android Java.io.FileNotFoundException: No content provider: /storage/emulated/0/Android/data


I want to take a photo and show in imageView this photo , it does't work corrretly on api 23 and 24 I try added a file provider this is what I did.

My activity :

public class TestActivity extends AppCompatActivity {

    ImageView iv;
    private File photoFile;
    private String mCurrentPhotoPath;
    private static final String TAG = "PHOTO";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        iv = (ImageView) findViewById(R.id.iv);

        photo();


    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (mCurrentPhotoPath != null) {
                File file = new File(mCurrentPhotoPath);
                if(file.exists())
                    Log.e(TAG , "photo jest");
                try {
                    Bitmap mImageBitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), Uri.parse(mCurrentPhotoPath));
                    iv.setImageBitmap(mImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(TestActivity.this, "Nie udało się zapisać zdjęcia ", Toast.LENGTH_LONG).show();
            }

        }
    }
    void photo() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (cameraIntent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
                // Create the File where the photo should go
                photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.i(TAG, "IOException");
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = null;
                    try {
                        photoURI = FileProvider.getUriForFile(getApplicationContext(),
                                BuildConfig.APPLICATION_ID + ".provider",
                                createImageFile());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                    startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
                }
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
}

on manifets I added a file provider :

  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="xxx.xxx.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

and This is my file provider :

<?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/xxx.xxx/files/Pictures" />
</paths>

And when I take a photo on logcat I see this :

08-23 08:47:01.298 25695-25695/W/System.err: java.io.FileNotFoundException: No content provider: /storage/emulated/0/Android/data/files/Pictures/JPEG_20170823_084656_-159214243.jpg
08-23 08:47:01.298 25695-25695/W/System.err:     at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1141)
08-23 08:47:01.298 25695-25695 W/System.err:     at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:991)
08-23 08:47:01.298 25695-25695/ W/System.err:     at android.content.ContentResolver.openInputStream(ContentResolver.java:711)
08-23 08:47:01.298 25695-25695/ W/System.err:     at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:890)
08-23 08:47:01.298 25695-25695 W/System.err:     at .Activity.TestActivity.onActivityResult(TestActivity.java:54)
08-23 08:47:01.298 25695-25695 W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:7137)

here I have a FileNotFoundException

 Bitmap mImageBitmap 

    =MediaStore.Images.Media.getBitmap(getApplicationContext().

 

 getContentResolver(), Uri.parse(mCurrentPhotoPath));

In first activity I check a permissions ;

  private boolean checkAndRequestPermissions() {

        int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        listPermissionsNeeded = new ArrayList<>();
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }

        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

private void logIn(){
    startActivity(new Intent(MainActivity.this, TestActivity.class));
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS && grantResults.length == listPermissionsNeeded.size()) {
        boolean allGranted = true;
        for (int grantedResult : grantResults) {
            if (grantedResult != PackageManager.PERMISSION_GRANTED) {
                allGranted = false;
            }
        }
        if (allGranted) {
            logIn();
        }
    }
}

Solution

  • You need to ask for the run-time permission for writing and reading storage before storing and reading the bitmap.