4

This is my first question here. I've searched for my doubt. I found similar questions but i haven't exactly got my answer. So please forgive me if i have done something wrong. I'm trying to save an image from an ImageView in my app to a folder in my sdcard. Here's the code :-

public void save(View view) {
    myImage.setDrawingCacheEnabled(true);
    Bitmap imgV = myImage.getDrawingCache();
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/AVP_saved");
    String fname="Image.png";
    File file = new File(myDir, fname);
        try {
               FileOutputStream out = new FileOutputStream(file);
               imgV.compress(Bitmap.CompressFormat.PNG, 90, out);
               out.flush();
               out.close();
               Toast.makeText(this, "Image Downloaded", 7000).show();

        } catch (Exception e) {
               e.printStackTrace();
               Toast.makeText(this, e.getMessage(), 8000).show();
        }
    }

'save' method is the method assigned to a button. 'myImage' is the ImageView found by its id. I have already set the permissions in the manifest. The thing is, the image dosen't get saved and it says that the path dosen't exist. When I myself create the folder "AVP_saved", then the image gets saved. What do i have to edit in this code such that the app creates the folder by itself when i click the button?

Thanks for your time!

Anas Khan
  • 98
  • 2
  • 9

1 Answers1

1

Add this code after File myDir = new File(root + "/AVP_saved");

if(!myDir.exists()) {
  mydir.mkdir(); //you can else call mkdirs() if you have to create a complete directory hierarchy
}

It seems that in Java, it's not possible to create a directory hierarchy by creating just a file in it. With this, you'll create your directory only if it doesn't exist (be careful, if the directory exists but it's a file, it will launch an exception maybe, so you can look for myDir.isDirectory() too).

Astrorvald
  • 223
  • 1
  • 9
  • Thank you, that answer helped me. I just had a doubt if you don't mind - why dosen't that image appear in my Gallery? – Anas Khan Nov 13 '12 at 13:32
  • 1
    I think you can find the solution here: http://stackoverflow.com/questions/2170214/image-saved-to-sdcard-doesnt-appear-in-androids-gallery-app – Astrorvald Nov 13 '12 at 14:24