Reputation: 187
I am trying to write a file to SDCard with below Code (permission android.permission.WRITE_EXTERNAL_STORAGE
already set in manifest.xml).
Upon execution of nmea_file.createNewFile();
it throws exception with Permission Denied
.
Any guesses why would this be happening?
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
Log.d(TAG, "Sdcard was not mounted !!" );
}
else
{
File nmea_file;
File root = Environment.getExternalStorageDirectory();
FileWriter nmea_writer = null;
try {
nmea_file = new File(root,"NMEA.txt");
if(!nmea_file.exists()) {
Log.w(TAG, "File Doesn't Exists!");
nmea_file.createNewFile();
}
nmea_writer = new FileWriter(nmea_file);
nmea_writer.append(nmea);
nmea_writer.flush();
}
catch (IOException e)
{
Log.w(TAG, "Unable to write", e);
}
finally
{
if (nmea_writer != null)
{
try
{
nmea_writer.close();
}
catch (IOException e)
{
Log.w(TAG, "Exception closing file", e);
}
}
}
}
Upvotes: 17
Views: 65269
Reputation: 1074
Check whether sdcard is mounted or not if you are checking in emulator. Also dont foget to give some size for sdcard at the time of creating the emulator. Then you need to add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in your manifest.
Upvotes: 1
Reputation: 1021
Be aware that your uses-sdk statement can effect you ability to write to the SD card(!).
My AndroidManifest.xml had the following:
<uses-sdk minSdkVersion="8"/>
And I could write to the SD card without any problems even though I had not declared android.permission.WRITE_EXTERNAL_STORAGE.
When I changed my uses-sdk statement to:
<uses-sdk android:targetSdkVersion="9" minSdkVersion="8" />
All my SD card writes failed with a permission denied! Granted that android.permission.WRITE_EXTERNAL_STORAGE should have been declared, but why with one uses-sdk statement it worked and the other it did not?
Upvotes: 2
Reputation: 1945
Add to manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 31
Reputation: 721
You might want to check that you have access to SDCARD. Here is how you can do it in code:
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
Upvotes: 12
Reputation: 16363
It may happen if SD card is blocked for some operations, like:
Upvotes: 20