file.exists() returns false for existing file in android

一世执手 提交于 2019-12-20 04:07:08

问题


In my app user can select image from sdcard and set as profile picture. Everything is working fine but when user selects image from whatsapp folder from sdcard image can not decoded.

I am using following code to decode file and display in ImageView.

if (imgFile.exists()) {                                 

Bitmap myBitmap = BitmapFactory.decodeFile(imgFile  
        .getAbsolutePath());                        

imgProfilePic.setImageBitmap(myBitmap);             
myBitmap = null;                                    
System.gc();                                        
Runtime.getRuntime().gc();                          

}

I am getting selected image path /storage/sdcard0/WhatsApp/Media/WhatsApp Images/IMG-20130804-WA0000.jpg and it exists in sdcard but file.exists always returns false. It works fine if user selects image from other folders rather than whatsapp.

Update

I am following steps like

1. click on profilepic(imageview).
2. select options(from camera,galerry,or edit)
3. open selected or captured image in CropImage Activity.
4. display cropped image.

Anyhelp would be greatly appreciated..Thanks.


回答1:


I was modifying image of other apps. I think this might be the problem. So what I did ?

  1. select image and get path in onActivityResult()
  2. copy image from this path in temp file using below code
  3. use temp file for cropping and other processing

private void copyFile(File sourceFile, File destFile) throws IOException {
    if (!sourceFile.exists()) {
        return;
    }

    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }

}

Hope this may help someone else.




回答2:


If your ImageFile.exists() method is giving false in android, but it exists in memory, then you definitely have not given Write-external-storage Permission in the Manifest file of Your Project. Add this Permission in the Manifest of Your Project:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


来源:https://stackoverflow.com/questions/20437626/file-exists-returns-false-for-existing-file-in-android

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