Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save image to sdcard android Directory problem

Tags:

android

Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:

FileOutputStream os;
dirName = "/mydirectory/";
        try {  
            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)){
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File (sdCard.getAbsolutePath() + dirName);
                dir.mkdirs();
                //File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
                File file = new File(dir, dirName+fileName);
                os = new FileOutputStream(file);
            }else{
                os = context.openFileOutput(fileName, MODE_PRIVATE);
            }
            resizedBitmap.compress(CompressFormat.PNG, 100, os);
            os.flush();
            os.close();
        }catch(Exception e){

        }

ErrorLog:

java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)

like image 483
user606669 Avatar asked Jun 12 '26 14:06

user606669


1 Answers

Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?

Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.

Edit - to create directories:

String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();

Then you can save a file to root + "/mvc/mvc/foo.png".

like image 109
Matthew Willis Avatar answered Jun 17 '26 23:06

Matthew Willis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!