how to get file path from sd card in android - android

hi all i have mp3 files in sd card. how to get file path of mp3 song from sd card.
please assist me.

You can get the path of sdcard from this code:
File extStore = Environment.getExternalStorageDirectory();
Then specify the foldername and file name
for e.g:
"/LazyList/"+serialno.get(position).trim()+".jpg"

Environment.getExternalStorageDirectory() will NOT return path to micro SD card Storage.
how to get file path from sd card in android
By sd card, I am assuming that, you meant removable micro SD card.
In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.
Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.
Environment.getExternalStorageDirectory() was there from API level 1
getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).
But note that,
Shared storage may not always be available, since removable media can
be ejected by the user. Media state can be checked using
getExternalStorageState(File).
There is no security enforced with these files. For example, any
application holding WRITE_EXTERNAL_STORAGE can write to these files.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

this code helps to get it easily............
Actually in some devices external sdcard default name is showing as extSdCard and for other it is sdcard1. This code snippet helps to find out that exact path and helps to retrive you the path of external device..
String sdpath,sd1path,usbdiskpath,sd0path;
if(new File("/storage/extSdCard/").exists())
{
sdpath="/storage/extSdCard/";
Log.i("Sd Cardext Path",sdpath);
}
if(new File("/storage/sdcard1/").exists())
{
sd1path="/storage/sdcard1/";
Log.i("Sd Card1 Path",sd1path);
}
if(new File("/storage/usbcard1/").exists())
{
usbdiskpath="/storage/usbcard1/";
Log.i("USB Path",usbdiskpath);
}
if(new File("/storage/sdcard0/").exists())
{
sd0path="/storage/sdcard0/";
Log.i("Sd Card0 Path",sd0path);
}

By using the following code you can find name, path, size as like this all kind of information of all audio song files
String[] STAR = { "*" };
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
cursor = managedQuery(allaudiosong, STAR, audioselection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
} while (cursor.moveToNext());

As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:
http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html
Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.
Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :
File getStoragePath() {
String removableStoragePath;
File fileList[] = new File("/storage/").listFiles();
for (File file : fileList) {
if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
return file;
}
}
return Environment.getExternalStorageDirectory();
}

maybe you are having the same problem i had, my tablet has a SD card on it, in /mnt/sdcard and the sd card external was in /mnt/extcard, you can look it on the android file manager, going to your sd card and see the path to it.
Hope it helps.

Related

Android, Xamarin: Get File Path Of SD Card

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

Android: delete image on sd card

Android 7.0, API 24. Permissions are granted in both AndroidManifest and real time.
Following are the scenarios which I have tried:
Only using the content resolver removes it from MediaStore but it comes back when the device is restarted.
When deleting an internal image "/storage/emulated/0/DCIM/Camera/..."
it works, but when trying to delete an external image (or what should
be external image) "/storage/4ED7-7F17/DCIM/Camera/..." it fails at
file.canWrite().
Using Environment.getExternalStorageDirectory().getAbsolutePath() returns "/storage/emulated/0" (+ "/DCIM/Camera/...") and it fails at file.exists().
Hardcoding "/SD card/DCIM/Camera/..." (which should be the correct filepath) fails at file.exists().
Weirdly, in the Android Device File Explorer, the files that should be in the SD Card folder are in the "/storage/4ED7-7F17/" folder which the files have a permission listing of -rwxrwx--x. And permission inside "/storage/emulated/" is "Permission denied". But to find the files in Android app MyFiles or Windows File Explorer the files are in "/SD card/DCIM/Camera/...".
Completely confused any help would be greatly appreciated.
File file = new File(filename);
if (file.exists()) {
if (file.canWrite()) {
if (file.delete()) {
// Set up the projection (we only need the ID)
String[] projection = {MediaStore.Files.FileColumns._ID};
// Match on the file path
String selection = MediaStore.Files.FileColumns.DATA + " = ?";
String[] selectionArgs = new String[]{filename};
Uri queryUri;
if (isVideo) {
// Query for the ID of the media matching the file path
queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else {
// Query for the ID of the media matching the file path
queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentResolver contentResolver = context.getContentResolver();
Cursor c = contentResolver.query( queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID));
Uri deleteUri = ContentUris.withAppendedId(
MediaStore.Files.getContentUri("external"), id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
Toast.makeText(context, "File not found: " + filename,
Toast.LENGTH_LONG).show();
}
c.close();
Toast.makeText(context, "File deleted: " + filename,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "File not deleted: " + filename,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "File cannot be wrote to: " + filename,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "File does not exist: " + filename,
Toast.LENGTH_LONG).show();
}
}
) "storage/4ED7-7F17/DCIM/Camera/..." it fails at file.canWrite().
Yes of course. Micro SD cards are read only on modern Android systems.
Apps nowadays can only write in one app specific directory on SD card.
If you want write access to the whole card you need to use the Storage Access Framework.
I stand correct. What's missing on N is MediaStore.getDocumentUri(Context context, Uri mediaUri), which provides conversion of fictitious file paths for the DCIM directory on Oreo+ to a Storage Access Framework URI that can be used to delete the file. N doesn't seem to provide an equivalent that I can find. And the content: Uris for media files don't work with Storage Access Framework unless converted.

Get path of DCIM folder on both primary and secondary storage

I am writing an application that should upload pictures taken by the camera which are stored in the DCIM/Camera folder on both internal memory and SD card.
This means that before every upload all available storages have to be checked for presence of any images.
I use Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) to access the primary storage, which can be either SD card or internal memory (depends on device).
From documentation:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
My question is, how can I access the secondary storage to check for presence of images in the DCIM/Camera folder without hard-coding the path, which does not work well since the SD card might be emulated in different path.
Try this code for choosing the last used DCIM/Camera folder.
String getDCIMCamera() {
try {
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE};
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
if (cursor != null) {
cursor.moveToFirst();
do {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (path.contains("/DCIM/")) {
File file = new File(path);
path = file.getParent();
cursor.close();
return path;
}
} while (cursor.moveToNext());
cursor.close();
}
}
catch (Exception e) {
}
return "";
}
See also #Pedram tips: https://stackoverflow.com/a/24189813/966789
Try
File[] aDirArray = ContextCompat.getExternalFilesDirs(context, null);
See http://developer.android.com/reference/android/support/v4/content/ContextCompat.html#getExternalFilesDirs(android.content.Context, java.lang.String)
Remember that external storage (SD Card) is not emulated and all paths are visible to all users.
Return Value
null - In case of failure
Root path (File) of each mounted external storage.
So if aDirArray.length > 1, then the following gets you the DCIM path you are looking for on the removable storage.
File aExtDcimDir = new File(aDirArray[1], Environment.DIRECTORY_DCIM);
Maybe in your case, you want to check aDirArray[0], aDirArray[1], ... (all Files returned in the array) for the presence of Environment.DIRECTORY_DCIM.
getExternalStorageDirectory retrieves only from internal storage data but not secondary storage images
This is the way we are getting secondary storage images from android or any folder accessing from secondary storage this is the code......
String secStore = System.getenv("SECONDARY_STORAGE");
File file = new File(secStore + "/DCIM");
File[] listFiles = file.listFiles();
File[] aDirArray = ContextCompat.getExternalFilesDirs(SDCardExample.this, null);
File path = new File(aDirArray[1], Environment.DIRECTORY_DCIM);
String data=path.toString();
int index=data.indexOf("Android");
String subdata=data.substring(0,index);
File sec=new File(subdata+"DCIM/Camera");
File[] secs=sec.listFiles();
File[] aDirArray = ContextCompat.getExternalFilesDirs(MainActivity.this, null);
File path = new File(aDirArray.length>1?aDirArray[1]:aDirArray[0], Environment.DIRECTORY_DCIM);
like Dave Truby wrote
Here is the solution.
Try it...
First get all files in a list
var file=new Java.IO.File("storage/");
var listOfStorages=file.ListFiles();
var isSDPresent=false;
if(listOfStorages[1].Name.Containes("emulated")||listOfStorages[0].Name.Containes("-"))
{
isSDPresent=true;
var sdCardName=listOfStorages[0].Name;
}
It works.

How to get the internal and external sdcard path in android

Most of the new android devices have an internal sdcard and an external sdcard. I want to make a file explorer app but I can't find out how to get the path to use in my app because
File file = Environment.getExternalStorageDirectory();
just returns in most device /mnt/sdcard
but there is another path for the other external sdcard like /storage1 or /storage2
. Any help appreciated.
How to get the internal and external sdcard path in android
Methods to store in Internal Storage:
File getDir (String name, int mode)
File getFilesDir ()
Above methods are present in Context class
Methods to store in phone's internal memory:
File getExternalStorageDirectory ()
File getExternalFilesDir (String type)
File getExternalStoragePublicDirectory (String type)
In the beginning, everyone used Environment.getExternalStorageDirectory() , which pointed to the root of phone's internal memory. As a result, root directory was filled with random content.
Later, these two methods were added:
In Context class they added getExternalFilesDir(), pointing to an app-specific directory on phone's internal memory. This directory and its contents will be deleted when the app is uninstalled.
Environment.getExternalStoragePublicDirectory() for centralized places to store well-known file types, like photos and movies. This directory and its contents will NOT be deleted when the app is uninstalled.
Methods to store in Removable Storage i.e. micro SD card
Before API level 19, there was no official way to store in SD card. But many could do it using unofficial APIs.
Officially, one method was introduced in Context class in API level 19 (Android version 4.4 - Kitkat).
File[] getExternalFilesDirs (String type)
It returns absolute paths to application-specific directories on all
shared/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.
That means, it will return paths to both Micro SD card and Internal memory. Generally, second returned path would be storage path of micro SD card.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
Yes. Different manufacturer use different SDcard name like in Samsung Tab 3 its extsd, and other samsung devices use sdcard like this different manufacturer use different names.
I had the same requirement as you. so i have created a sample example for you from my project goto this link Android Directory chooser example which uses the androi-dirchooser library. This example detect the SDcard and list all the subfolders and it also detects if the device has morethan one SDcard.
Part of the code looks like this For full example goto the link Android Directory Chooser
/**
* Returns the path to internal storage ex:- /storage/emulated/0
*
* #return
*/
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* Returns the SDcard storage path for samsung ex:- /storage/extSdCard
*
* #return
*/
private String getSDcardDirectoryPath() {
return System.getenv("SECONDARY_STORAGE");
}
mSdcardLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String sdCardPath;
/***
* Null check because user may click on already selected buton before selecting the folder
* And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
*/
if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
mCurrentInternalPath = mSelectedDir.getAbsolutePath();
} else {
mCurrentInternalPath = getInternalDirectoryPath();
}
if (mCurrentSDcardPath != null) {
sdCardPath = mCurrentSDcardPath;
} else {
sdCardPath = getSDcardDirectoryPath();
}
//When there is only one SDcard
if (sdCardPath != null) {
if (!sdCardPath.contains(":")) {
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File(sdCardPath);
changeDirectory(dir);
} else if (sdCardPath.contains(":")) {
//Multiple Sdcards show root folder and remove the Internal storage from that.
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
} else {
//In some unknown scenario at least we can list the root folder
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
}
});
For all Android versions,
Permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
Use requestLegacyExternalStorage for Android 10 (add to AndroidManifest > application tag):
android:requestLegacyExternalStorage="true"
Get internal directory path:
#Nullable
public static String getInternalStorageDirectoryPath(Context context) {
String storageDirectoryPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
if(storageManager == null) {
storageDirectoryPath = null; //you can replace it with the Environment.getExternalStorageDirectory().getAbsolutePath()
} else {
storageDirectoryPath = storageManager.getPrimaryStorageVolume().getDirectory().getAbsolutePath();
}
} else {
storageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
}
return storageDirectoryPath;
}
Get external directories:
#NonNull
public static List<String> getExternalStorageDirectoryPaths(Context context) {
List<String> externalPaths = new ArrayList<>();
String internalStoragePath = getInternalStorageDirectoryPath(context);
File[] allExternalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
for(File filesDir : allExternalFilesDirs) {
if(filesDir != null) {
int nameSubPos = filesDir.getAbsolutePath().lastIndexOf("/Android/data");
if(nameSubPos > 0) {
String filesDirName = filesDir.getAbsolutePath().substring(0, nameSubPos);
if(!filesDirName.equals(internalStoragePath)) {
externalPaths.add(filesDirName);
}
}
}
}
return externalPaths;
}
Since there is no direct meathod to get the paths the solution may be
Scan the /system/etc/vold.fstab file and look for lines like this:
dev_mount sdcard /mnt/sdcard 1
/devices/platform/s3c-sdhci.0/mmc_host/mmc0
When one is found, split it into its elements and then pull out the
path to the that mount point and add it to the arraylist
emphasized textsome devices are missing the vold file entirely so we add a path here
to make sure the list always includes the path to the first sdcard,
whether real or emulated.
sVold.add("/mnt/sdcard");
try {
Scanner scanner = new Scanner(new File("/system/etc/vold.fstab"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (element.contains("usb"))
continue;
// don't add the default vold path
// it's already in the list.
if (!sVold.contains(element))
sVold.add(element);
}
}
} catch (Exception e) {
// swallow - don't care
e.printStackTrace();
}
}
Now that we have a cleaned list of mount paths, test each one to make
sure it's a valid and available path. If it is not, remove it from
the list.
private static void testAndCleanList()
{
for (int i = 0; i < sVold.size(); i++) {
String voldPath = sVold.get(i);
File path = new File(voldPath);
if (!path.exists() || !path.isDirectory() || !path.canWrite())
sVold.remove(i--);
}
}
I'm not sure how general an answer this but I tested it on a motorola XT830C with Android 4.4 and on a Nexus 7 android 6.0.1. and on a Samsung SM-T530NU Android 5.0.2.
I used System.getenv("SECONDARY_STORAGE") and Environment.getExternalStorageDirectory().getAbsolutePath().
The Nexus which has no second SD card, System.getenv returns null and Envirnoment.getExterna... gives /storage/emulated/0.
The motorola device which has an external SD card gives /storage/sdcard1 for System.getenv("SECONDARY_STORAGE") and Envirnoment.getExterna... gives /storage/emulated/0.
The samsumg returns /storage/extSdCard for the external SD.
In my case I am making a subdirectory on the external location and am using
appDirectory = (System.getenv("SECONDARY_STORAGE") == null)
? Environment.getExternalStorageDirectory().getAbsolutePath()
: System.getenv("SECONDARY_STORAGE");
to find the sdcard. Making a subdirectory in this directory is working.Of course I had to set permission in the manifest file to access the external memory.
I also have a Nook 8" color tablet. When I get a chance to test on them, I'll post if I have any problems with this approach.
but there is another path for the other external sdcard like /storage1 or /storage2
There is nothing in the Android SDK -- at least through Android 4.1 -- that gives you access to those paths. They may not be readable or writable by your app, anyway. The behavior of such storage locations, and what they are used for, is up to device manufacturers.
File main=new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()));
File[]t=main.getParentFile().listFiles();
for(File dir:t)
{
Log.e("Main",dir.getAbsolutePath());
}
Output:
E/Main: /storage/sdcard1
E/Main: /storage/sdcard0
I have one SD card and inbuilt memory.
There is no public api for get internal/external sdcard path.
But there is platform api called StorageManager in android.os.storage package. see http://goo.gl/QJj1eu .
There are some features such as list storage, mount/unmount storage, get mount state, get storage path, etc.
But it is hidden api and it should be deprecated or broken in next android release.
And some methods need special permission, and most are not Documented.
Try this code it will help
Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);

Android device specific camera path issue

I know that my question is a duplicate of this question and this one. But still I have some problems, so don't try to close or downvote my question friends. Please go through the question fully.
In my app I want to store Images into the same folder as where the device native Camera stores them. As per my research, I have found out that each device stores the Images into a different name and in different folder.
That is:
Nexus-One stores its camera files into a folder named Camera (/sdcard/DCIM/Camera).
All HTC devices store their camera files into a folder named 100MEDIA (/sdcard/DCIM/100MEDIA).
Sony Xperia x10 stores its camera files into a folder named 100ANDRO (/sdcard/DCIM/100ANDRO).
Motorola MilesStone stores its camera files into a folder named Camera (/sdcard/DCIM/Camera).
So I wanted to know if it's programmatically possible to get this path so that I can store the images taken from my app to the same location?
When I was googling I found out that it's better to create an external folder of my own so that I can store the images in that path with the name I am specifying. After that also in HTC device of API version 3 (Android 1.5) I found out that only the folder is getting created but the image gets saved in its default place with a name of its own.
How to solve this issue? Is it not possible to find the specific path and name of the image that gets saved for each device? Please help me friends.
Use getExternalStorageDirectory() if API level is below 7 and then append /Pictures to get the path of Photos storage.
for API level > 7 use getExternalStoragePublicDirectory (DIRECTORY_PICTURES).
I use the following code
String pictures_path = Utils.getRealPathFromURI(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
File path = new File(pictures_path);
if (path.isFile())
path = path.getParentFile();
Where Utils:
public static String getRealPathFromURI(Uri content_uri, int media_type) {
String column = MediaType.MEDIA_TYPE_PICTURE;
ContentResolver content_resolver = getContext().getContentResolver();
String [] proj = { column };
Cursor cursor = content_resolver.query(content_uri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(column);
if (!cursor.moveToFirst())
return null;
return cursor.getString(column_index);
}
EDIT: Unfortunatelly, the approach above may not always work :( ...
Eventually I did manual checkings:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
if (path.exists()) {
File test1 = new File(path, "100MEDIA/");
if (test1.exists()) {
path = test1;
} else {
File test2 = new File(path, "100ANDRO/");
if (test2.exists()) {
path = test2;
} else {
File test3 = new File(path, "Camera/");
if (!test3.exists()) {
test3.mkdirs();
}
path = test3;
}
}
} else {
path = new File(path, "Camera/");
path.mkdirs();
}
This is the function that I am using. It doesnt specifically name 100Media or Camera directories. It simply starts in the /DCIM folder and looks at its children. If the child is not a .thumbnails directory (or is, depending on what youre doing), then look at its children and get them. It also gets pictures in the /DCIM directory itself.
File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File thumbnails = new File(dcim, "/.thumbnails");
File[] listOfImg = dcim.listFiles();
if (dcim.isDirectory()){
//for each child in DCIM directory
for (int i = 0; i < listOfImg.length; ++i){
//no thumbnails
if( !listOfImg[i].getAbsolutePath().equals(thumbnails.getAbsolutePath()) ){
//only get the directory (100MEDIA, Camera, 100ANDRO, and others)
if(listOfImg[i].isDirectory()) {
//is a parent directory, get children
File[] temp = listOfImg[i].listFiles();
for(int j = 0; j < temp.length; ++j) {
f.add(temp[j].getAbsolutePath());
}
}else if(listOfImg[i].isFile()){
//is not a parent directory, get files
f.add(listOfImg[i].getAbsolutePath());
}
}
}
}
I have been looking for a solution to this problem myself. Since different manufacturers have differnet naming conventions for camera folders, this seems to cover all ground best. It works for me pretty well.

Categories

Resources