• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps [Code] Quick tip: How to check if storage is writable

alostpacket

Over Macho Grande?
Before writing any files to the user's storage (usually sdcard) you should always check to make sure it's available to write to!

This will save a lot of headaches with strange errors in your code cause by the user forgetting they mounted the sdcard via USB.

This is just part of one of my methods in my FileUtil class. I will try and post these kinds of tips as regularly as I can :)

Code:
//From class FileUtil.java


/**
 * Checks to see if the storage is available to be written to
 * You should still check individual files .canWrite() methods
 * @return true if the external storage is writable
 */

public static boolean isStorageWritable()
{
    boolean storageWriteable  = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) 
    {
        storageWriteable = true;
    }    
    
    return storageWriteable;
}
You can then call it in an if statement like this:

Code:
if ( FileUtil.isStorageWritable() )
{
    //write some files to disk
}
else
{
    //inform user there's a problem
}
For more info, see the Environtment class documentation:

http://developer.android.com/reference/android/os/Environment.html


.
 
Back
Top Bottom