Android-Droid Android-Droid - 1 year ago 84
Android Question

Android saving file to external storage

I have a little issue with creating a directory and saving a file to it on my android application. I'm using this piece of code to do this :

String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;

fos = new FileOutputStream(file);

But it's throwing an exception : /mnt/sdcard/MyApp/MediaCard/MediaCard-0.png (No such file or directory)

on that line :
fos = new FileOutputStream(file);

If I set the filename to :
it's working, but If I try to create and save the file to an another directory it's throwing the exception. So any ideas what I'm doing wrong?

And another question: Is there any way to make my files private in external storage so user can't see them in gallery, only if he connect his device as
Disk Drive

Answer Source

Use this function to save your bitmap in SD card

private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

    } catch (Exception e) {

and add this in manifest

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

EDIT: By using this line you can able to see saved images in the gallery view.

sendBroadcast(new Intent(
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));

look at this link also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download