File is not getting deleted in Android Java? - java

File is not getting deleted in Android, I have checked all premissions, and I tried all the solutions available in the internet but nothing helps. Your help will be highly assist me. Thanks in advance.
I used the below permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
And this is the code I used
File dir = Environment.getExternalStorageDirectory();
String path = dir.getAbsolutePath() + "/Recordings/Call/" + filename;
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + path);
} else {
System.out.println("file not Deleted :" + path);
}
}
And the err log is
W/soft.my_app_name: Got a deoptimization request on un-deoptimizable method void libcore.io.Linux.remove(java.lang.String)
Error log is

Related

Delete from DCIM directory?

I've made an app which modifies photos taken that are saved to the DCIM directory.
I'd now like to delete the original version of the photo.
AndroidManifex:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There's a warning here for external storage saying this permission no longer provides write access. So on launch my app requests that permission from the user:
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE_BY_LOAD_PROFILE);
Here is the code for deleting original photo:
File inFile = new File(mediaItem.Directory, mediaItem.FileName);
if (inFile.exists()) {
try {
inFile.delete();
context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.ImageColumns.DATA + "=?", new String[]{ mediaItem.Directory + mediaItem.FileName } );
} catch (SecurityException ex) {
}
}
I have tried both File.delete() and context.getContentResolver().delete(), neither of them seem to actually delete the file, and no error is ever thrown.

Json file not being attached to email for android

I am trying to send an attached json file to an email, however for some reason the json file is not being attached when the email is sent/created.
Note: I do NOT want the user to select the file to attach, I want it to be fixed/set automatically.
I have the following permissions in my AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and the code
private void backupJsonToEmail(String jsonString) {
// create file
if(!getFilesDir().exists()){
getFilesDir().mkdir();
}
String filePath = getFilesDir() + File.separator + BACKUP_NAME;
System.out.println("file path: " + filePath);
// /data/user/0/com.my.stuff/files/backup.json
try {
FileOutputStream fos = new FileOutputStream(filePath);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeBytes(jsonString);
outStream.close();
// send to email
try {
File file = new File(filePath);
long fileKbSize = file.length() / 1024;
System.out.println("FILE SIZE IS: " + fileKbSize + " kb"); // 69 kb...
Uri uri = Uri.fromFile(file);
String to[] = {"test#yahoo.com"};
Intent originalIntent = ShareCompat.IntentBuilder.from(this)
.setType("application/json")
.setEmailTo(to)
.setStream(uri)
.setSubject("test")
.setText("here is the attached json")
.getIntent();
originalIntent.setData(Uri.parse("mailto:"));
originalIntent.setAction(Intent.ACTION_SENDTO);
Intent finalIntent = Intent.createChooser(originalIntent, "choose an email application");
startActivity(finalIntent);
} catch (Throwable t) {
Toast.makeText(this, "Request failed try again: " + t.toString(), Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT1:
after making the suggestion changes that #piyushpk suggested, I now get the following errors when I choose an email app:
for Yahoo Mail: "The attachment is too big to send"
for Gmail: "Permission denied for the attachment"
however the file size is only 69 kb, according to my print statement...
I think you are trying to use Inbuilt email application to send a json file and yahoo is complaining about size and Gmail is denying it as json is considered not a safe extension.
Instead use Some SMTP Email api like send grid etc. to send file without any inbuilt android application.
https://github.com/sendgrid/sendgrid-java
Mail Gun Sendgrid are quite good option

Unsuccessful download with Download Manager Android 9

I am trying to download a file from the internet with DownloadManager on Android 9, but I only get unsuccessful download. This is what I am testing:
My Manifest permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
My code to download it:
private final String FILE_NAME = "SampleDownloadApp.apk";
String apkUrl = "https://androidwave.com/source/apk/app-pagination-recyclerview.apk";
public void download(Context context) {
DownloadManager dm = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE);
Uri mUri = Uri.parse(apkUrl);
DownloadManager.Request r = new DownloadManager.Request(mUri);
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Uri uri = Uri.parse("file://" + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + FILE_NAME_2);
r.setDestinationUri(uri);
dm.enqueue(r);
}
I have tried android: usesCleartextTraffic = "true" in the manifest but then nothing happens. I never get any errors neither in logcat nor in run.
I followed this tutorial: https://androidwave.com/download-and-install-apk-programmatically/
I have no idea what the problem may be, any solution?
Help with this!
there is something wrong with you URL tried following and its working
private final String FILE_NAME = "SampleDownloadApp.apk";
String apkUrl = "https://d-10.winudf.com/b/APK/Y29tLm5lbW8udmlkbWF0ZV80MzUxMV9iOTJjMTFkZA?_fn=VmlkTWF0ZSBIRCBWaWRlbyBEb3dubG9hZGVyIExpdmUgVFZfdjQuMzUxMV9hcGtwdXJlLmNvbS5hcGs&_p=Y29tLm5lbW8udmlkbWF0ZQ&am=cCsiKSeBEin6IVuzn-Q2PA&at=1590661203&k=3c1a8eca32edf42751cb3f5fa102d0205ed0e1d3";
public void download(Context context) {
DownloadManager dm = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE);
Uri mUri = Uri.parse(apkUrl);
DownloadManager.Request r = new DownloadManager.Request(mUri);
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, FILE_NAME);
dm.enqueue(r);
}

Android file scan

I have a music player application. I need to scan all music files which are in phone but Android 5.0 and later versions i can't access SD-card
permissions in manifest.xml
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
before 5.0 version this part works
ArrayList<HashMap<String, String>> ist=new ArrayList<>(new getplaylist().getPlayList("/"));
this part return only phones storage not sdcard
ArrayList<HashMap<String, String>> ist=new ArrayList<>(new
getplaylist().getPlayList(Environment.getExternalStorageDirectory()
.getPath()));
playlist method
public class getplaylist {
public ArrayList<HashMap<String,String>> getPlayList(String rootPath) {
ArrayList<HashMap<String,String>> fileList = new ArrayList<>();
try {
File rootFolder = new File(rootPath);
File[] files = rootFolder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if (getPlayList(file.getAbsolutePath()) != null) {
fileList.addAll(getPlayList(file.getAbsolutePath()));
} else {
break;
}
} else if (file.getName().endsWith(".mp3")) {
HashMap<String, String> song = new HashMap<>();
song.put("file_path", file.getAbsolutePath());
song.put("file_name", file.getName());
fileList.add(song);
}
}
return fileList;
} catch (Exception e) {
System.out.print(e.toString());
return null;
}
}}
Like official android documentation says for API level 21 and above:
getExternalMediaDirs
Returns absolute paths to application-specific directories on all
shared/external storage devices where the application can place media
files. These files are scanned and made available to other apps
through MediaStore.
use getExternalMediaDirs instead of getExternalStorageDirectory in:
getplaylist().getPlayList(Environment.getExternalStorageDirectory().getPath()));
first of all check external storage available or not with the device. After that these are the following method which can access external memory Directory-
getExternalStorageDirectory();
getExternalStoragePublicDirectory(String type);
Environment.getExternalStorageDirectory().getAbsolutePath();
must include permission into manifest file.
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
or
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);

File extension not changing - Android

I'm trying to create an app in Android, and part of it's functionality is renaming .jpg file extensions to .jpeg file extensions. However, it's not working.
filepath is the path of the .jpg file, and doThings() is what it does after the file has been renamed.
Here is my code:
// Create new string to store edited file path
String newfilepath = filepath;
// Create new file to be used for renaming
File file1 = new File(filepath);
// Remove JPG extension
newfilepath = newfilepath.substring(0, newfilepath.length() - 3);
// Replace with JPEG extension
newfilepath += "jpeg";
// Add new file for renaming purposes
File file2 = new File(newfilepath);
// Rename file from JPG to JPEG
boolean rename = file1.renameTo(file2);
// Check if file renaming was successful
if(rename) {
// Does things
doThings(newfilepath);
}
Note: I also tried changing file1.renameTo(file2); to this:
boolean test = file1.renameTo(file2);
System.out.println("Renamed? " + test);
And received this in logcat:
I/System.out: Renamed? false
Also, to prove it's not a permissions issue, here is the AndroidManifest.xml file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
And I do request permissions in the Android 6+ format here:
public void getPermissions(View view) {
String[] perms = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
if (EasyPermissions.hasPermissions(this, perms)) {
// We have permissions, send message
Toast.makeText(this, "Select an image.", Toast.LENGTH_SHORT).show();
selectFile();
} else {
// We don't have permissions
Toast.makeText(this, "Permissions are required", Toast.LENGTH_SHORT).show();
// Ask again
ActivityCompat.requestPermissions(MainActivity.this,
perms, PERMISSIONS_MULTIPLE_REQUEST);
}
}
Help is appreciated, thanks!
EDIT: I've been testing and getting weird results. I will update this later today.

Categories