I want to read all the music files from the sd card but I tried to put the file in several places on the SD card and the program still doesn't find the music on the card. Anyone any suggestions? Where exactly to put the files?
I was just doing that last night :).
In android, the sdcard is mounted on '/sdcard'. I don't have the code here, but it was something like this.
public List<String> getMp3Files() {
File sdcard = new File("/sdcard");
return getMp3Files(sdcard);
}
private List<String> getMp3Files(File directory) {
List<String> mp3files = new ArrayList<String>();
File[] files = directory.listFiles();
if(files == null) {
return Collections.EMPTY_LIST;
}
for( File file : files) {
if( file.isFile() && file.getName().toLowerCase().endsWith(".mp3")) {
mp3files.add(file.getAbsolutePath());
} else if ( file.isDirectory()) {
mp3files.addAll(getMp3Files(file));
}
}
return mp3files;
}
it's not optimized AT ALL for mobiles, but it works. And be careful that if you run this code starting on the root folder, it will end up in a infinite loop of folders! (you can always try :D).
Maybe this could help you
http://blog.jayway.com/2009/04/22/working-with-sd-cards-in-the-android-emulator/
Related
I am currently working on an app, that goes through your phone and lists all available MP3 files. I managed to get this done and search for everything on the internal storage, but didnt manage to find a way using the envoirment to get to the sd card, when one is installed. This is my code - u will see a missing part when SD card is TRUE. Can you complete it?
public List<string> ReturnPlayableMp3(bool sdCard)
{
List<string> res = new List<string>();
string phyle;
if(sdCard)
{
// missing
}
else
{
try
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.ToString();
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
res.Add(phyle);
}
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n" + e9.Message, ToastLength.Long).Show();
}
}
return res;
}
}
It would need to return the exact same thing as it does for the internal storage only this time for the sd card. Right now, what is beeing returned is:
""/storage/emulated/0""
I hope you can help me. Thank you!
SO I found the place it is: /storage/05B6-2226/
But the digits refer to only MY sd card. How do I get this path programatically?
Take a look at these methods:
Context.GetExternalFilesDir
Returns the absolute path to the directory on the primary external
filesystem (that is somewhere on Environment.ExternalStorageDirectory)
where the application can place persistent files it owns. These files
are internal to the applications, and not typically visible to the
user as media.
Context.GetExternalFilesDirs
Returns absolute paths to application-specific directories on all
external storage devices where the application can place persistent
files it owns. These files are internal to the application, and not
typically visible to the user as media.
I've been searching for a couple of days with a lot of solutions that just ended up giving you the 'external' built in storage. Finally found this solution for the 'removable' SD Card and wanted to post it here in case someone else is still looking.
How to write on external storage sd card in mashmallow in xamarin.android
//Get the list of External Storage Volumes (E.g. SD Card)
Context context = Android.App.Application.Context;
var storageManager = (Android.OS.Storage.StorageManager)context.GetSystemService(Context.StorageService);
var volumeList = (Java.Lang.Object[])storageManager.Class.GetDeclaredMethod("getVolumeList").Invoke(storageManager);
List<Java.IO.File> ExtFolders = new List<Java.IO.File>();
//Select the Directories that are not Emulated
foreach (var storage in volumeList)
{
Java.IO.File info = (Java.IO.File)storage.Class.GetDeclaredMethod("getDirectory").Invoke(storage);
if ((bool)storage.Class.GetDeclaredMethod("isEmulated").Invoke(storage) == false && info.TotalSpace > 0)
{
//Get Directory Path
Console.WriteLine(info.Path);
}
}
Just wanna share my answer, where I have get the extStorages Path and I use this method in my simple file browser app.
public static string[] GetRemovableStorages()
{
List<string> extStorage = new List<string>();
//If this throws exception
string storageDir = (string)Environment.StorageDirectory;
//Try this
string storageDir = Directory.GetParent (Environment.ExternalStoragePublicDirectory).Parent.FullName;
string[] directories = Directory.GetDirectories(storageDir);
foreach(string dir in directories)
{
try
{
var extStoragePath = new Java.IO.File(dir);
bool isRemovable = Environment.InvokeIsExternalStorageRemovable(extStoragePath);
if(isRemovable) extStorage.Add(extStoragePath.AbsolutePath);
else return null;
}
catch
{
}
}
return extStorage.ToArray();
}
Elikill58's answer throws exception no such method "getDirectory" in my case but I recommend Elikill58's answer
I am using the following code for trying to list the files in Download directory.
I build the apk, install it on my phone and then run it. I have files in both Internal memory/Download folder and External memory/Download folder when I view in File Browser of my phone, but the app does not display the file list. When I debug I find that the listFiles() function returns null.
Please let me know where I am doing wrong. The variable state has value mounted so the issue has nothing to do with the memory not being mounted.
String state = Environment.getExternalStorageState();
private boolean isMediaAvailable() {
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else {
return false;
}
}
if (!isMediaAvailable()) {
Utility.finishWithError(this,"Media Not Available");
} else {
String path =Environment.getExternalStorageDirectory().toString()+ File.separator + Environment.DIRECTORY_DOWNLOADS;
File file = new File(path);
mRootPath = file.getAbsoluteFile().getPath();
mFileNames = new ArrayList<String>();
File filesInDirectory[] = file.listFiles();
if (filesInDirectory != null) {
for (int i = 0; i<filesInDirectory.length;i++) {
mFileNames.add(filesInDirectory[i].getName());
}
}
}
Use :
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
to get the downloaded directory,
and use File.list() to get an array with the list of files in the directory.
Plzzz help me with this. Already late searching for the solution:
I want to list each and every Folder and file which is in the Android Phone's Internal Memory and External Memory.
The below code only gets list of files in one single directory.. But I'm unable to understand how would I list all the folders and files from internal and external memory.
..... List files = getListFiles(new File("YOUR ROOT")); ....
private List getListFiles(File parentDir) {
ArrayList inFiles = new ArrayList();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")){
inFiles.add(file);
}
}
}
return inFiles; }
Any help?
Look at the File object. It gives you methods to get all the files in a directory, tells you whether a file is a directory, and many other things.
You could easily do a recursive tree walk of the directory system. You probably will run into permissions issues, though, unless you have "rooted" your device.
I finally found this somewhere else.. This is how it's done (fully functional code)
public void walk(File root) {
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
Log.d("realcrazy", "Dir: " + f.getAbsoluteFile());
walk(f);
}
else {
Log.d("realcrazy2", "File: " + f.getAbsoluteFile());
}
}
}
In my application, when a user want to upload Audio, that user should only be able to choose .mp3 extension file. If the user choose any other file like .ppt, .pdf, it wont be allowed.
I have got this approved code for File explore from SD Card: Choose file dialog.
But I want only .mp3 extension files or list of .mp3 extension files.
So what should I do?
maybe you can check for files like this
File f = new File("/sdcard/");
for (File file : f.listFiles())
{
if(file.getName().endsWith(".mp3"))
{
// do something with them, add them to list or whatever
}
}
Check file pattern and then compare, if it is mp3 then add into arraylist, check below function, which will return list of mp3.
Vector<String> mStrings =new Vector<String>();
int mTotalimage=0;
public void fileExtension(File dir) {
String mp3Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
String mCheck=listFile[i].getAbsoluteFile().toString();
mCheck=mCheck.substring(mCheck.lastIndexOf("/")+1);
System.out.println("listFile[i].getAbsoluteFile().toString()"+listFile[i].getAbsoluteFile().toString());
System.out.println("mCheck..."+mCheck);
if (listFile[i].isDirectory() && !(mCheck.startsWith(".")) ) {
fileExtension(listFile[i]);
} else {
//fetch jpg from folders.
if (listFile[i].getName().endsWith(mp3Pattern)){
mStrings.add(listFile[i].getAbsolutePath().toString());
mTotalimage++;
//fetch png image from folders.
}
}
}
}
System.out.println("size on return......."+mStrings.size());
}
I have an application that needs to read images from a folder created by the application on the sdcard(sdcard/"foldername"/"filename.jpg". I have no idea what the names of the files are because the user specifies the names of the files. I need to read the images from the folder and make something like the default image viewer. Im thinking read them into a grid view first but 1) cant figure out how to dynamically read them from a folder 2) how would I implement the image options like the default viewer? If there was a way to open the default viewer on a certain folder that would help.
any input would be amazing been working on it for a while.
Thanks
Here's how you can get a list of folders off of the memory card:
String state = Environment.getExternalStorageState();
if(state.contentEquals(Environment.MEDIA_MOUNTED) || state.contentEquals(Environment.MEDIA_MOUNTED_READ_ONLY))
{
String homeDir = Environment.getExternalStorageDirectory();
File file = new File(homeDir);
File[] directories = file.listFiles();
}
else
{
Log.v("Error", "External Storage Unaccessible: " + state);
}
This code is from the top of my head, so some syntax may be off a bit, but the general idea should work. You can use something like this to filter down the folders to only folders that contain images:
FileFilter filterForImageFolders = new FileFilter()
{
public boolean accept(File folder)
{
try
{
//Checking only directories, since we are checking for files within
//a directory
if(folder.isDirectory())
{
File[] listOfFiles = folder.listFiles();
if (listOfFiles == null) return false;
//For each file in the directory...
for (File file : listOfFiles)
{
//Check if the extension is one of the supported filetypes
//imageExtensions is a String[] containing image filetypes (e.g. "png")
for (String ext : imageExtensions)
{
if (file.getName().endsWith("." + ext)) return true;
}
}
}
return false;
}
catch (SecurityException e)
{
Log.v("debug", "Access Denied");
return false;
}
}
};
Then, change the first example to:
File[] directories = file.listFiles(filterForImageFolders);
That should return only directories that contain images. Hopefully this helps some!