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.
Related
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
I have permissions for read and writing on AndroidManifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
... because I want to copy one file. I'm performing this process in two steps:
1. Launching an Intent so the user creates the file where he wants:
This code is mostly the example of the Android developers site.
private void createFile() {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/vnd.sqlite3");
intent.putExtra(Intent.EXTRA_TITLE, "test.db");
startActivityForResult(intent, CREATE_FILE);
}
2. Copy the file.
The intent returns a Uri, so inside the onActivityResult:
try {
destinationOutputStream = getContentResolver().openOutputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
(where data is the Intent), I'm able to get the output stream.
Finally, and according to the documentation, I should be able to copy the file:
try {
Long totalBytes = Files.copy(originalPath, destinationOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
(where originalPath is the path (of type Path) where the original file is stored).
But, on runtime, I'm getting the following error:
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
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);
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.
The app used to run. However, just recently it began to stop working. The device is running Android Nutella. Below is the LogCat.
java.lang.SecurityException: Permission Denial: reading com.google.android.music.store.ConfigContentProvider uri content://com.google.android.music.ConfigContent/one-key/2/ExplicitRestrictedByParentControl from pid=2500, uid=10373 requires the provider be exported, or grantUriPermission()
The app crashes in the the following code snippet on the last line(contained in a SongParser method).
String[] projection2 = {MediaStore.Audio.Media.ARTIST};
Uri songUri=null;
try {
songUri = Uri.parse("content://com.google.android.music.MusicContent/audio");
} catch (NullPointerException e){
e.printStackTrace();
}
if (songUri!=null) {
CursorLoader cl2 = new CursorLoader(context,
songUri, projection2, null, null, null);
cursor = cl2.loadInBackground();
I grant the Uri permissions in the following method after asking for permissions through the runtime permissions methods.
private void startService() {
//start intent to RssService for feedback
intent = new Intent(getActivity(), SongService.class);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().grantUriPermission("xxx.xxx.xxx.SongService",Uri.parse("content://com.google.android.music.MusicContent/audio"),Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(SongService.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
Here is where SongService calls SongParser.
#Override
protected void onHandleIntent(Intent intent) {
List<String> eventItems= null;
if (haveNetworkConnection()) {
parser = new SongParser();
eventItems = parser.getAllArtists(getApplicationContext());
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) eventItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);}}
I have contained the permissions in the manifest as well. Again, this exception seemingly happened on its own.
<permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
What's happening is that for some reason, the (exported) MusicContent provider will redirect to ConfigContentProvider, which is not exported.
It seems that the way to solve it is to open Google Play Music. If you haven't launched it in a while, it will redirect to com.google.android.music.store.ConfigContentProvider and trigger a SecurityException. It's kind of problematic but at least I can tell my users what to do. Let me know if you can come up with something better.
It might also be a good idea to file a bug.
You do not have access to that ContentProvider. It is not exported, and that app did not pass you a Uri that you can use to access it.
Since presumably the Uri is from an app that you did not write, apparently an update to that app changed this behavior.