Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SD card writing, Permission Denied

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);
            }
        }
    }
  }
like image 210
user329604 Avatar asked Dec 22 '10 06:12

user329604


3 Answers

Add to manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
like image 56
Butsaty Avatar answered Sep 21 '22 19:09

Butsaty


It may happen if SD card is blocked for some operations, like:

  1. Preparing to dismount SD card from slot
  2. Device connected to PC as external USB drive
like image 38
Barmaley Avatar answered Sep 17 '22 19:09

Barmaley


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();
}
like image 30
Temperage Avatar answered Sep 20 '22 19:09

Temperage