canread() function is always giving false - android

val inputFile: File = File("/storage/emulated/0/Download/Ball - 113146.mp4")
// Check whether the input file exist or not
if (!inputFile.canRead()) {
throw FileNotFoundException("Unable to read $inputFile")
}
i'm expecting true from this canRead() function but it's always giving false. I have already taken the required permissions(READ_EXTERNAL_STORAGE).`

Your File does not exist.
Try to use file.exists() to check if the file exists or not.
Also, just the permission READ_EXTERNAL_STORAGE is not enough if you are targeting Android Version 11.
This is because you are trying to get a file in the "Downloads" folder, so you need to use Scoped Storage.
More infos here.

Related

How to delete a file in /download (ora any other folder) in the android external storage with DocumentProvider through Kotlin?

I'm [still] new on android development and about Java and about Kotlin (also an explanation in Java could be ok, however, I'm studying it also, Kotlin is prefered) and I'm struggling for deleting a simple downloaded file into the ExternalStorage.
Of course I enabled permission for read & write, and, even if this code returns a "True", I still can see the untouched file into my Download folder
here the code:
___UPDATE
// uri of my file in external storage ~/Download dir
var uri = Uri.parse (Environment.getExternalStorageDirectory().getPath() + "/Download/$myFilename$myExtensionVar")
// file object pointing at uri of file in external storage
val downloadedFile = File(uri.toString())
var deletedBool:Boolean = downloadedFile.delete()
println("myTag - deleted Boolean: $deletedBool")
if (deletedBool){
println("myTag - uri of file-to-be-deleted: $uri")
var secondStepToDelete:Int = context.getContentResolver().delete(uri, null, null)
println("myTag - second Step for deletion: $secondStepToDelete")
}
The file i am trying to rid of is a multimedia file (.mp3) and I added the second block of code (the one inside the IF statement) since I found that should work, having to do with the "DocumentProvider" (I'm new and I still don't know how to proper call its methods..) but, of course, It doesn't work at all.
I think I do need the ID (long type i guess) for the file stored into the external storage, however I haven't found yet how to get it
Thanks in advance for the help!
To build a File object, use the File constructor. To build a File object for a location off of a certain root directory, use the two-parameter File(File, String) constructor:
val downloadedFile = File(Environment.getExternalStorageDirectory(), "Download/$myFilename$myExtensionVar")
Unless you are getting a Uri from DownloadManager or something, there is no Uri that you need to delete().
I have more written here on external storage and how to work with it.
In Kotlin
file.deleteRecursively()

Listfiles() in android is not working

Im developing a Music player for which I need to retrieve all mp3 files from my storage. Im using getExternalStorageDirectory() function to obtain the external storage directory. But When I tried listfiles() on this path,its returning a null object. Im using a API Level 21 . And I have already gave
uses-permission in android manifest
both for reading and writing external storages,Even after doing this Im getting a null object.
Code:
File root= new
File(Environment.getExternalStorageDirectory().getPath());
Log.v("file exists ", root.exists()+""); Log.v(" file is
a directory",root.isDirectory()+""); Log.v("file can be
read",root.canRead()+""); Log.v("listfile value",root.listFiles()+"");
Outputs:
1.True
2.True
3.False
4.null
Directory is exists( I checked using isDirectory and exists() functions )
But canRead() function is returning false value, which means I dont have authority to read the directory, How to correct this?
Any solution?
Thanks in advance.

Deleting a File in Android returns false

I'm trying to delete a file in my Android app. The file was preciously created by the same Android app, and has MODE_WORLD_READABLE permissions.
I'm trying to delete it as follows:
File chosenFile = context.getFileStreamPath("myfile.txt");
boolean fileDeleted = chosenFile.delete();
if (fileDeleted)
Log.d(TAG, "myfile.txt was deleted");
else
Log.d(TAG, "myfile.txt was not deleted");
chosenFile.delete() keeps returning false. Is it because it's still being accessed? If so, is there any way I can force close it?
Thanks.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Did you give this permission.
for this line of code is myfile.txt exists, please check that first, file write permissions are not required for writing in private file system. Its required only when you try to write external storage.
context.getFileStreamPath("myfile.txt");
and to delete the file use
context.deleteFile("myfile.txt");
OK, so I figured out my mistake - the file doesn't exist in the first place. I thought I guarded against that by checking if (chosenFile == null), but I should've checked if (chosenFile.exist() == true) instead.

getExternalFilesDir(null) returns null

Once again, I've come up against a question which has been asked and answered before but in my implementation it is still not working.
I'm calling getExternalFilesDir(null) right at the very start of my main activity's onCreate method. It returns null every time, whether I run it in an AVD or on my phone (Samsung Galaxy Plus).
Yes, I have the <uses-permission android:name="android.permissions.WRITE_EXTERNAL_STORAGE" /> line in my AndroidManifest.xml and yes, I am checking the external storage state before I make the call and it is mounted.
Here are the first three lines inside my onCreate() method. Actually, it's just after the super.onCreate() and setContentView() calls.
String state = Environment.getExternalStorageState();
File extFiles = getExternalFilesDir(null);
File locFiles = getFilesDir();
So, once these three lines have executed, these are the values for the variables:
state == "mounted"
extFiles == null
locFiles == "/data/data/com.mypackage.name/files"
Would anyone have any ideas as to why this might be?
-----EDIT-----
So I've tried another approach; Rather than using getExternalFilesDir(null), I tried using File basePath = new File(Environment.getExternalStorageDirectory(), "myAppName");
This is not ideal and I know that the Android documentation says, and I agree with it, that you should rather use getExternalFilesDir(). Seeing as that's not working for me though I had to try something else. This time the function does return a valid File object so, after the above line, the path of basePath is /mnt/sdcard/myAppName. So far, so good. When I check with DDMS I can see that /mnt/sdcard exists but not /mnt/sdcard/myAppName. This is to be expected. So I call boolean result = basePath.mkdirs();
But this returns false and when I check on the file system I can confirm that the myAppName subfolder has not been created. When I create the folder manually through DDMS and put files in it, I can read those files from my application but I can't write anything in that folder.
Please help! I'm at my wit's end.
If this wasn't a typo when you posted your question, you'll probably hate yourself for this:
<uses-permission android:name="android.permissions.WRITE_EXTERNAL_STORAGE" />
should be
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is from Android documentation:
Returns the path of the directory holding application files on external storage.
Returns null if external storage is not currently mounted so it could not ensure
the path exists; you will need to call this method again when it is available.
The other option is you can check if External storage is available:
String state = Environment.getExternalStorageState();
File filesDir;
// Make sure it's available
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
filesDir = getExternalFilesDir(null);
} else {
// Load another directory, probably local memory
filesDir = getFilesDir();
}
My issue was that I opened a FileOutputStream, then before I closed the FileOutputStream, I opened a FileInputStream to see what was already in the file.
I moved opening the FileInputStream to before the FileOutputStream is opened and that fixed my issue.
Delete a line
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in AndroidManifest.xml.
Switch a xml editor to "Android Manifest Permissions" with "Permission" tab in eclipse, and add a
uses-permission "android.permission.WRITE_EXTERNAL_STORAGE"
with some clicks.
Then try running your application.
It seems eclipse (may depends on a defference of version or state or settings) can ignore some words described by direct xml in AndroidManifest.xml.
Thanks for an advise. You are right, my answer looked like to agree in small talk.

Why Android cannot read the file to a File object?

This is my code to create a File Object. I am sure that the file is existing. However the file length() returns 0 and the exists() returns false too.
File uploadFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/DSC00050.jpg");
int totalSize = (int) uploadFile.length(); // Get size of file, bytes
After Writing File uploadFile = new File(...); it will not create the file itself.
AFAIK If File.exists() is returning false, then file just doesn't exist yet.
but yes You can create file by calling file.createNewFile()
if exists() returns false means the file does not exist or not accessible. Make sure that the SD card is mounted and that your app has sufficient permission i.e. READ_EXTERNAL_STORAGE. I suspect this is the problem because you should get exception in that case.
The other thing is to log the absolute file path uploadFile.getAbsolutePath() and make sure that it is correct.
Edit:
Are you sure that your image is directly under the DCIM folder not DCIM/Camera ? Use any file browser in Android and check the file complete path. I do not see any other problems in the code.

Categories

Resources