Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sd.canWrite() always returns false

Tags:

java

android

I've set the following my android manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I've got the following in my activity:

File sd = Environment.getExternalStorageDirectory();
boolean can_write = sd.canWrite();

sd returns /mnt/sdcard

I'm testing on my device (evo 3d) not the emulator. The sd card is mounted. It happens both when in charge only mode and when the usb cable isn't plugged in. Various pages on google and posts on stack show that exact same method to check if the sd card is writable so I must be missing something.

UPDATE:

I try the following code and it throws ioexception permission denied.

    File TestFile = new File(sd + "/testfile.txt");
    try {
        boolean result = TestFile.createNewFile();
        if(result)
        {
            Log.i("tag","successfully created file");
        } else {
            Log.i("tag","failed to create file");
        }
    } catch (IOException e) {
        Log.e("tag",e.toString() + " " + TestFile);
        return false;
    }

I've formatted my sdcard, re-mounted it, and rebooted phone and still have the same error.

UPDATE

Apparently it's my own ignorance that caused it to fail. I had my permissions block in the wrong section of my manifest. Thanks again :)

like image 783
matt Avatar asked Aug 04 '11 13:08

matt


1 Answers

I wouldn't use sd.canWrite(), actually, I would use something like this:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    Log.d("Test", "sdcard mounted and writable");
}
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    Log.d("Test", "sdcard mounted readonly");
}
else {
    Log.d("Test", "sdcard state: " + state);
}

Taken from here:http://www.xinotes.org/notes/note/1270/

like image 156
Otra Avatar answered Oct 05 '22 23:10

Otra