Cannot delete files transfered from computer in Android - android

I'm making a video downloader app and I've got no problems saving and deleting files downloaded by the app to external storage but any file transfered from my computer cannot be deleted by the app.
This is a real problem as it's one of the key features I want. Here's the code I'm using:
public boolean deleteDataFromStorage(Data toDelete) {
//The file object soon to be deleted
File f = null;
Log.e(TAG, "Deleting " + toDelete.fileName);
// Delete file from storage
try {
// Get file to delete
f = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + DIRECTORY + toDelete.fileName);
} catch (IOException e) {
Log.e(TAG, e.toString());
// Print to stack trace
e.printStackTrace();
}
// Delete file
if(f.delete()) {
return true;
} else {
Log.e(TAG, "Failed to delete " + toDelete.fileName);
return false;
}
}
As the f.delete() function doesn't throw any exceptions I have no idea what the problem is. The only thing I can think of is that the app doesn't have the permission to delete a file created in windows and yet I have downloaded apps from the app store that have no problem deleting transfered files.
Any help would be greatly appreciated.

As per your comment, since f.isFile() and f.exists() returns false, your f is not a file, in other words, you're getting the path wrong.
Print to the logs f.getAbsolutePath(), check what it is, and then it should be easy to fix.

Related

Android: delete file taken by camera doesn't work properly (4.4.x)

I delete the file (camera file) like that:
public static void deleteFile(File file) {
if (file != null && file.exists()) {
if (!file.delete()) {
LogUtils.LOGE(TAG, "Delete file failed: " + file.getAbsolutePath());
} else {
LogUtils.LOGD(TAG, "Delete file successful: " + file.getAbsolutePath());
}
}
}
The delete indicates successful, but if I check on Gallery App on my phone, I can see this strange stuff:
It's on my Android 4.4.x. With my another mobile on Android 6.x there is no problem.
Could you help me guys?
As #CommonsWare said, since you are saving your file in the public storage, the gallery app will find the file and keep track, after you remove the gallery needs to update the references to now show the image anymore.
To avoid that you should always save your files in the private storage, you can find more info about storages here: https://developer.android.com/training/basics/data-storage/files.html

Inconsistent MediaConnection behaviour, some files don't show in Android File Transfer

I have a directory structure of files in external storage. They don't show up in the Android File Transfer app, so I think it's a media scanner problem.
I'm creating them with a FileOutputStream in a directory based on Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).
I have the following method, called from an activity, so context is an activity (forget that this blocks the main thread for now!):
public void scan(Context context, File base) {
File[] files = base.listFiles();
if (files == null) {
return;
} else {
for (File file : files) {
if (file.isFile()) {
String path = file.getAbsolutePath();
MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
Log.e("Langstroth", path);
} else if (file.isDirectory()) {
this.scan(context, file);
}
}
}
}
public void scan(Context context) {
this.scan(context, this.baseDir);
}
}
The output of the log is as expected:
E/MyApp﹕ /storage/emulated/0/Documents/Langstroth/sample/5000/1430576404874.wav
E/MyApp﹕ /storage/emulated/0/Documents/Langstroth/sample/5000/1430577209491.wav
And then lots of:
E/MyApp﹕ Scan completed path /storage/emulated/0/Documents/Langstroth/sample/5000/1430576404874.wav uri content://media/external/audio/media/7836
E/MyApp﹕ Scan completed path /storage/emulated/0/Documents/Langstroth/sample/5000/1430577209491.wav uri content://media/external/audio/media/7838
This proves that the files exist. They don't show up in the Android File Transfer though.
Here's the strange thing. Another method:
public void otherDemo(Context context, File baseDir) {
String newPath = baseDir.getAbsolutePath() + "/some/random/dirs";
Log.e("Langstroth", "New path " + newPath);
File dir = new File(newPath);
dir.mkdirs();
Log.e("Langstroth", dir.exists() ? "Dir exists": "Dir does not exist");
File f = new File(dir, "myfile.txt");
try {
new BufferedOutputStream(new FileOutputStream(f)).close();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Langstroth", f.exists() ? "File exists": "File does not exist");
MediaScannerConnection.scanFile(context, new String[]{f.getAbsolutePath()}, null, null);
}
and the log output:
E/MyApp﹕ New path /storage/emulated/0/Documents/Langstroth/some/random/other/dirs
E/MyApp﹕ Dir exists
E/MyApp﹕ File exists
E/MyApp﹕ File: /storage/emulated/0/Documents/Langstroth/some/random/other/dirs/myfile.txt
E/MyApp﹕ Other scan completed path /storage/emulated/0/Documents/Langstroth/some/random/other/dirs/myfile.txt uri content://media/external/file/7842
One test file shows up, the others don't
Proof:
Where are the other files?
Generally speaking, before you let another process work with a file, you want to ensure all bytes are flushed to disk, via getFD().sync(). In particular, this seems to help with the whole media scanning thing.
the files shows up in a .listFiles(), and .exist(), and the callback for the MediaScanner says that it completed correctly. Surely an extant (if empty) file should show up?
The ways of the media scanner are mysterious. :-) IOW, beats me.
Bear in mind that there are multiple moving parts here: your app, the media scanner, the MTP daemon on Android, and your MTP client. The breakdown could be at any stage. If you unplug and re-plug in the device, and now the files show up in your MTP client, my guess would be that the MTP client is working off of a slightly stale cache.

How to check a file before delete in android

I know how to delete a file, it's:
File file = new File(path);
file.delete();
Can I test that the file is currenlty in use without rooting my device?
For exmple I want to check if the file is open before i can delete it.
I want to be able to catch errors with a try catch sentence.
You can use a try/catch clause.
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
You can find more information here.

check if a folder is empty (internal storage)

I've the sequent trouble. My app should read a list of files and show their name to the user.
When the app is launched for the first time i need to create a specific folder for the app?
then how can i check if it's empty?
Assuming you created the directory in the internal storage, you can get the number of child objects in the directory like this
File dir = context.getDir("somePath", Context.MODE_PRIVATE);
File[] children = dir.listFiles();
if(children.length > 0)
{
// the directory is not empty
}
else
{
// the directory is empty.
}
This is just a quick sample code. The better way would be to exclude the self and parent aliases using a custom FileFilter with dir.listFiles(), as I'm not sure they will always be excluded from the resulting list.
The following code will check if a folder already exists and if not creates one and warns you if error creating one:
// check if appfolder is created and if not through an
// exception
File path = new File("yourDir");
if (!path.exists()) {
if (!path.mkdirs()) {
try {
throw new IOException(
"Application folder can not be created. Please check if your memory is writable and healthy and then try again.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
} else {
Log.i("app", "directory is: " + path.getPath());
}
exists() checks if a path exists or not and path.exists() simply creates one for you.

Created folder is not visible in the file explorer..

I have a problem with creating a folder and a file on the sdcard.
Here's the code:
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/folder");
boolean success;
if (!folder.exists()) {
success = folder.mkdirs();
}
File obdt = new File(folder, "file.txt");
try {
success = obdt.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
With this code I expect to create the folderfolder in the Download folder of the sdcard and in this the file file. I want that the user can access the file. So I want to put it in a shared folder.
The success variable is true and when I run the code again the folder already exists and doesnt come in the if-block.
But I can't see the created folder and file on the sdcard in file explorer.
Info:getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() returns storage/sdcard/Download
I work with a Galaxy Nexus.
Damn! :)
Now I solved my problem...I was misunderstanding the operation of creating files in the file system.
When I spoke of file explorer I meant the file explorer of the operating system and NOT the file explorer in the DDMS :).
I thought when I create a file I will see it in the file explorer of the operating system but when the device is connected to the PC the files can only be seen in the DDMS file explorer.
Sorry I'm new to Android ;)
When the App is running standalone without PC connection and afterwards I connect with the PC I see the created files and folders of course :)
Thanks for help
Any errors from logcat?
Else: try something like Log.I("PATHNAME",folder.absolutePath()); and then look in your logcat to make sure where you are creating the folder where you think it is.
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you have already done that see if :
File obdt = new File(/sdcard/folder/file.txt)
try {
success = obdt.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
works.
You cannot see the folder/file in explorer? Maybe it is because the MediaScanner is active, but not adding your files. You can do this in your program or switch the Media Scanner of somewhere in your phone settings.
MediaScanner
Trigger MediaScanner
Try this out.
File dir = new File(Environment.getExternalStorageDirectory()
+ "/XXX/Wallpapers/");
File[] files = dir.listFiles();
if (files == null)
{
int numberOfImages = 0;
BitmapDrawable drawable = (BitmapDrawable) imageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment
.getExternalStorageDirectory();
new File(sdCardDirectory + "/XXX/Wallpapers/").mkdirs();
File image = new File(sdCardDirectory
+ "/XXX/Wallpapers/Sample" + numberOfImages + ".JPG");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"Image saved successfully in Sdcard/XXX/Wallpapers",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
Dont forget to add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Apparently there is a known bug in MTP.
Issue 195362
All phones using MTP instead of USB Mass storage do not properly show the list of files when that phone is connected to a computer using a USB cable. Android apps running on the device also cannot see these files.
It is actually as old as 2012
I've encountered the same problem: created files and folders don't show immediately after being written to sdcard, despite the file being flushed and closed !!
They don't show on your computer over USB or a file explorer on the phone.
I observed three things:
if the absolute path of the file starts with /storage/emulated/0/ it doesn't mean it'll be on your sdcard - it could be on your main storage instead.
if you wait around 5 minutes, the files do begin to show over USB (i.e. Windows explorer and built-in file explorer)
if you use adb shell ls /sdcard from terminal, then the file does show! you could use adb pull ... to get the file immediately. You could probably use DDMS too.
Code I used was:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileOutputStream os = new FileOutputStream(newFile);
os.write(json.getBytes());
os.flush();
os.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
and
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileWriter fw = new FileWriter(newFile);
fw.write(json);
fw.flush();
fw.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
why is it like this? Seems like another one of those "Android-isms" that you have to suffer through the first time you experience it.

Categories

Resources