Newtt
Newtt

Reputation: 6200

Android code not creating file. No such file or directory found error

I've got the following code to write a captured image to the SD card

private static File getOutputMediaFile(){
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "AppName");

    if (!mediaStorageDir.exists()){
        if (!mediaStorageDir.mkdirs()){
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    return new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
}

which is used as follows:

public void takePicture(){
    i= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Open camera
    file = Uri.fromFile(getOutputMediaFile());
    i.putExtra(MediaStore.EXTRA_OUTPUT, file);
    startActivityForResult(i, 100);
}

After the image is captured, the path to the file is sent to the following function:

public void sendForUpload(String uploadUrl, String path){
    File dir = Environment.getExternalStorageDirectory();
    File imgFile = new File(dir, path);
    sendFile(uploadUrl, imgFile);
}
public void sendFile(String uploadUrl, File file){
    Log.d(GlobalClass.TAG, "File has arrived here");
    Log.d(GlobalClass.TAG, file.toString());
    byte[] fileData1 = new byte[(int) file.length()];
    FileInputStream fileInputStream;
    try{
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(fileData1);
        fileInputStream.close();
    }catch (Exception e){
        Log.d("Error", e.getMessage());
    }
    .... // Upload
}

The try block here fails and the log shows the error:

D/Error: /storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg: open failed: ENOENT (No such file or directory)

How do I read the file into sendFile()?

Upvotes: 1

Views: 3442

Answers (2)

Md. Al-Amin
Md. Al-Amin

Reputation: 858

I have solution for this problem. It is easy to solve this issue.

Just go to your AndroidManifest.xml

and on =>application

Just enter this line => android:requestLegacyExternalStorage="true"

Your Problem will be solved.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007533

Look closely at the path in your error:

/storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg

You will notice that /storage/emulated/0 is repeated.

Replace:

File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir, path);

with:

File imgFile = new File(path);

Upvotes: 2

Related Questions