Android file scan - java

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);

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.

How to delete file or directory from root directory of external storage (...removable sdcard root directory)

i'm building a storage manager app but i can't delete/rename/create
files on external storage
i used file.delete() code for internal storage and it's works greate,
but it's not working on external storage files,
also tried
DocumentFile fileUri = DocumentFile.fromFile(file);
fileUri.delete();
and it's dosent work either
how can i write to external storage without using
the Intent.ACTION_OPEN_DOCUMENT_TREE each time
the user wants to delete/rename/create file?
the files path are /storage/5A85-D438/*files or a folders*
already added the folowing permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
including android:requestLegacyExternalStorage="true"
You can just use DocumentFile with createFile on an Output Stream.
if (!t.getString("muri", "").equals("")) {
try{
muri = t.getString("muri", "");
Uri treeUri = Uri.parse(muri);
final int takeFlags =
intent.getFlags() &
(Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
this.getContentResolver()
.takePersistableUriPermission(treeUri, takeFlags);
DocumentFile mr = DocumentFile.fromTreeUri(this, treeUri);
DocumentFile nf = mr.createFile("text/plain", "JAMZ");
OutputStream os =
getContentResolver().openOutputStream(nf.getUri());
os.write(pass.getBytes());
os.close();
wuri = nf.getUri().toString();
t.edit().putString("wuri", wuri).commit();
} catch (Exception e) {}}

"Permission Denied" error when write image file into sdcard

I was using a demo project to acquire and save image into SDcard, it works well. But after creating a new project with the same code, it keeps giving "Permission Denied" error and IO exception.
The xml and gradle files are copied from the demo project and only several activities are deleted, the permissions are stated in the xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also dynamically requested in the code
public class PermissionManager {
private static final int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] PERMISSIONS_ARRAYS = new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static List<String> permissionsList = new ArrayList<>();
private PermissionManager() {
}
public static void onResume(final Activity activity) {
boolean isHasPermission = true;
for (String permission : PERMISSIONS_ARRAYS) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
isHasPermission = false;
break;
}
}
if (!isHasPermission) {
for (String permission : PERMISSIONS_ARRAYS) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
}
}
ActivityCompat.requestPermissions(activity,
permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_PERMISSIONS);
}
}
I found there are several questions about this issue but as shown above, the permission request and statement are all set and they work well in the old project, could anyone give some hint?
There's a new feature for devices running on Android 10+ when you are handling media files and probably caused your problem. For Android 10, you can temperarily opt-out the scoped storage by adding this line to the manitest file:
<application android:requestLegacyExternalStorage="true" ... >

Android app: How do I create a directory in the internal storage

I can't seem to be able to figure out how to create a directory/file through an android app to the internal storage. I have the following code:
public class Environment extends SurfaceView implements SurfaceHolder.Callback {
public static String FILE_PATH;
//other unimportant variables
public Environment(Conext context) {
super(context);
FILE_PATH = context.getFilesDir() + "/My Dir/";
File customDir = new File(FILE_PATH);
if(!customDir.exists())
System.out.println("created my dir: " + customDir.mkdir());
File test = new File(FILE_PATH + "testFile.txt");
try {
if(!test.exists())
System.out.println("created test: " + test.createNewFile());
} catch(Exception e) {
e.printStackTrace();
}
//other unimportant stuff
}
}
I then use ES File Explorer to see if it created the file and I don't see the directory/file anywhere despite it printing out "true" for the System.out.println() calls.
What am I doing wrong?
The path where you are creating file is in apps private location. Generally you can't access it from outside. It's actually created in apps data folder. However it seems you want to write in external folder.
To write in the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
code:
String folder_main = "My Dir";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
File test = new File(f , "testFile.txt");
Here you will find how to you will create folder/file in external storage.
Save a File on External Storage
You can try with below:
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE);
File file = new File(directory,”fileName”);
String data = “TEST DATA”;
FileOutputStream fos = new FileOutputStream(“fileName”, true); // save
fos.write(data.getBytes());
fos.close();
This will write file in Device's internal storage (/data/user/0/com.yourapp/)
Hope this helps!

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