frgr
frgr

Reputation: 65

File not found exception when reading external storage

Earlier the code was working totally fine, and even now it works fine for pre Android 6 devices, but in my Nexus 5, 6.0.1, I am unable to access data from external storage.

It shows File not Found Exception

java.io.FileNotFoundException: /storage/emulated/0/Download/********/*****: open failed: ENOENT (No such file or directory)

For writing the data to storage, I am asking for runtime storage permission and that part seems to be fine.

Upvotes: 1

Views: 1681

Answers (2)

gaurang
gaurang

Reputation: 2240

Make this in you onCreate() method of main activity:

if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
    checkPermission();
    if (!checkPermission()) {
        requestPermission();
    }
}

And this code out side onCreate():

private boolean checkPermission(){
    int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
    if (result == PackageManager.PERMISSION_GRANTED){
        return true;
    } else {
        return false;
    }
}

private void requestPermission(){
    ActivityCompat.requestPermissions(activity,new String[]{
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CALL_PHONE},PERMISSION_REQUEST_CODE
    );
}

This code will check whether the version is above Lollipop OS. If so, then it will ask for permission to user while loading app.

Hope it will help you. Tested. Working properly.

Upvotes: 1

Ashish Ranjan
Ashish Ranjan

Reputation: 5543

Since your code is working fine in Pre-Marshmallow devices, looks like you've not added runtime permissions in your app.

Starting from Android M, you need to request for permissions at runtime, as mentioned in the docs :

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

Read more about Requesting permissions at runtime in Android here

Upvotes: 1

Related Questions