A list of downloaded files is null - android

I'm trying to get a list of downloaded files, here's code in Kotlin:
val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val files = dir.listFiles()
I have files in the folder but this code returns null. How come?

Set the permission to read from external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Related

Android Kotlin - Can not delete file from download folder

I am unable delete txt file from download directory. File.delete() does not work. I have also tried with context.deleteFile(), that does not work either. I am not getting any exception, just nothing happens. This works on many Android devices, but it does not work on the device that I needed it to work, which is Android device with embedded printer. Android version 8.1.
I have found this answer, stackoverflow, which is similar to official documentation Google.
I have tried to use Uri.fromFile(directory) and directory.toUri()
instead of MediaStore.Images.Media.EXTERNAL_CONTENT_URI from the example, since file is in download folder, but I got null pointer exception.
How I can get correct download folder Uri? Or is there another way to delete file?
Thank you in advance for any help and suggestions.
EDIT:
getAbsolutePath() = /storage/emulated/0/Download/print.txt
Code:
val downloadPath: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
// dowloadPath is passed as directory
fun readFile(directory: File, context: Context): String {
val fileToRead = File(directory, "print.txt")
//...
if (fileToRead.exists()) {
//...
fileToRead.delete()
}
}
Permissions:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
And inside <application
android:requestLegacyExternalStorage="true"
android:requestRawExternalStorageAccess="true"

Flutter - Save a local text file visible for user on Android

I'm trying to create a text file in a folder where the user can see for the file explorer apps of the mobile device, preferably in Documents folder.
Here is what I've till now (consider that we have all required permissions)
final directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
final filePath = '${directory!.path}/example.txt';
File file = File(filePath);
await file.create();
await file.writeAsString('Some random text content');
After that I try to find this new file on my file explorer apps, but it seems to not exists and no error logs can been seen.
If you want see an example code I wrote this PoC -> https://github.com/felipeemidio/save-local-file-poc
What I've tried so far?
If you try to execute file.exists() command it'll return true.
Use image_gallery_saver lib to "download" my file results on an error for trying to save a plain/text file where should only be image/* files.
Use getExternalStorageDirectory(type: StorageDirectory.documents) instead of getExternalStorageDirectory() changes nothing.
downloads_path_provider lib does not support null-safety.
If you set the directory path with the static value '/storage/emulated/0/Documents/example.txt', is possible to see the file through Archives app, but will not show when you select the option to see all Documents files.
Try file path as
String filePath = '/storage/emulated/0/Downloads/example.text';
and don't forget to add permissions in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Get list of files from specific Folder in Android Q

I am trying to access the specific folder in android Q but the app is getting crashed.
I am using below code which is working fine till Android PIE but it is not working in Android Q
val directory = File(path)
val files = directory.listFiles()
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Getting bellow error
NullPointerException: Attempt to get length of null array
With Android Q file interface can't be used to access public directories, unless you use the requestLegacyStorage in your app manifest (not raccomanded since it won't work anymore with Android R). To access the directory you need to use the DocumentFile class, for example:
DocumentFile f = DocumentFile.fromTreeUri(context, uri);
f.listFiles();

Android: Save data to internal memory using Download

I am downloading file from a server in Android using the DownloadManager class. I want to store this file in the internal memory of the device. I tried to use .setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory() +"/Android/data/xxx.xxx.xxx/files/") as mentioned here, but it is not working. How to solve my problem?
add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to manifest.xml and create "/Android/data/xxx.xxx.xxx/files/" path
try this
File testDirectory = new File(Environment.getExternalStorageDirectory() +"/Android/data/xxx.xxx.xxx/files/");
and
if (!testDirectory.exists()) {
testDirectory.mkdirs();
}

How to create a file in an SDCARD directory

I want to create a file(not created) in a directory(not created) in the SDCARD.
How doing it ?
Thank you.
Try the following example:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
//create folder
File folder = new File(dir); //folder name
folder.mkdirs();
//create file
File file = new File(dir, "filename.extension");
}
Don't forget to add the permission to your AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is that mkdirs() is called on a File object containing the whole path up to the actual file. It should be called on a File object containing the Path (the directory) and only that. Then you should use another File object to create the actual file.
You should also have to add permission to write to external media.
Add following line in the application manifest file, somewhere between <manifest> tags, but not inside <application> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use This:
DocumentFile tempDir = DocumentFile.fromSingleUri(context,targetDirectoryUri);
DocumentFile newDocumentFile = tempDir.createFile(type,name);
"targetDirectoryUri" is uri of the directory you want to put the file into it.
This is the only solution!
After Api 19 you can not write on SDCard, so you must use DocumentFile
instead File.
In addition, you must also take SDCard permission. To learn how to do this and get the targetDirectoryUri, please read this.
You can use in Kotlin
val file = File( this.getExternalFilesDir(null)?.getAbsolutePath(),"/your_image_path")
if (!file.exists()) {
file.mkdir()
}
Don't forget to give permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
See here why creating files on root of the SD card is a bad idea

Categories

Resources