Donnie Ibiyemi
Donnie Ibiyemi

Reputation: 1001

Save image to external Storage if Available

I would like to save wallpapers to the external storage if it is available else save it to the device internal storage.My code works with devices with external storage mounted but fails when external storage is not available. my short code is posted below

  public FileOutputStream getOutStream(String fileName) throws FileNotFoundException{
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        String sdpath = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)
                + "/";
        mSavePath = sdpath + "DroidPack";
        File file = new File(mSavePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File saveFile = new File(mSavePath, fileName);

        return new FileOutputStream(saveFile);


    }else{
        String sdpath = mContext.getFilesDir().getPath() + "/";
        mSavePath = sdpath + "DroidPack";
        File file = new File(mSavePath);
        if (!file.exists()) {
            file.mkdir();
        }
        return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE); 
        }
}

}

Upvotes: 0

Views: 76

Answers (1)

Leonardo
Leonardo

Reputation: 3191

Take a look at the Android Documentation

Nevertheless, you should try this:

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

You are just checking one condition !

Hope it helps !

Upvotes: 1

Related Questions