File length is 0 when recreating file from URI, or original filepath [getExternalFilesDir(String type) vs getFilesDir()]

淺唱寂寞╮ 提交于 2019-12-01 06:45:40

Even though I don't have all the information, I'm gonna make the call that the file is missing from the path you've given. The javadoc for length() specifically mentions this case will return 0.

So try checking exists() before you do anything with the file.

While using internal storage the file path is different. I think it is stored in /storage/emulated in latest devices. Check for your file path. and see if you are creating a file with the absolute path.

Found a workaround. This is the function I was using to get the file that was being passed to the Camera intent.

    // Create a File object for storing the photo
    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 = getApplicationContext().getFilesDir();

    mPhotoFileExists = true;

    // check if access to external storage exists
    // if returned true, return the new file
    // if returned false, user could have been requested for access
    // so, need to check if permission is available now
    // if still not available, return null

    if(haveWritePermissions())
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    return null;
    }

I changed the storageDir from getApplicationContext().getFilesDir(); to getApplicationContext.getExternalFilesDir(null);

Docs: getExternalFilesDir(String type), getFilesDir()

I passed null since I didn't want to put Environment.DIRECTORY_PICTURES, which would allow the Media Scanner to find the image file.

I understand that this, in no way, is a 'fix'. Still looking for an answer as to why getFilesDir() is causing this issue.

EDIT: Very pressing reason as to why this is not a good solution - external storage may not always be available, and there would not be any workaround in that case. Also, any other app with permission WRITE_EXTERNAL_STORAGE can write here. So, no security is enforced either.

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