Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permission to write to the SD card

Tags:

java

android

I would like my app to archive the application DB to the SD card. In my code I check if the directory canWrite() exists, and if not, throw an IOException. In this particular instance, I am trying to copy the db file to the root directory on the SD card, but it's throwing an IOException. How can I change the permission on a folder/file to be able to write to it?

like image 593
bugzy Avatar asked Jan 23 '10 02:01

bugzy


People also ask

How do I grant access to an SD card in VLC?

Go to settings > general > apps & notifications > app info > and then select the app you want to give permissions.. then look at where it says "permissions" and select it.. then go to where it says "storage" and enable it.


2 Answers

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory(); 

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
like image 139
Dave Webb Avatar answered Sep 18 '22 12:09

Dave Webb


The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")] public class MonoActivity : Activity {   protected override void OnCreate(Bundle bindle)   {     base.OnCreate(bindle);   } } 
like image 40
samus Avatar answered Sep 18 '22 12:09

samus