Zero
Zero

Reputation: 1904

Saved Bitmap doesn't appear on SD Card

I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
    boolean created = file.createNewFile();
    Log.d("Checks", "File created: " + created);
    fileOutPutStream = new FileOutputStream(file);
    fileOutPutStream.write(byteArrayOutputStream.toByteArray());
    fileOutPutStream.close();
} catch (FileNotFoundException e) {
    Log.d("Checks", "FileNotFoundException");
    e.printStackTrace();
} catch (IOException e) {
    Log.d("Checks", "IOException");
    Log.d("Checks", e.getMessage());
    e.printStackTrace();
}

I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?

EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.

Upvotes: 1

Views: 234

Answers (2)

Gleb
Gleb

Reputation: 445

Are you sure you are setting the permission to write to SD card? Try setting this one:

   WRITE_EXTERNAL_STORAGE

Edit: Ok, try this:

    Environment.getExternalStorageDirectory().getAbsolutePath()

Instead of:

    Environment.getExternalStorageDirectory().toString()

Or even create a directory like this:

    File dir = new File(Environment.getExternalStorageDirectory() + 
                        File.separator + 
                        "myFolder");
    dir.mkdirs();

Upvotes: 1

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21934

From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().

Upvotes: 1

Related Questions