Error saving images to the external storage (sdcard)

50 views Asked by At

I'm trying to compress and store some photos in the external memory of an Android device using this method:

private String saveToExternalStorage(Bitmap bitmapImage, String nameImage, int compression) {
    String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/imagesDir";
    File file = new File(root, nameImage);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.JPEG, compression, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file.getAbsolutePath();
}

But I'm getting the following error:

E/AndroidRuntime: FATAL EXCEPTION: Thread-6
Process: com.universitat_autonoma_de_barcelona_geology_mineralogy.minescope, PID: 13633
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileOutputStream.close()' on a null object reference
    at com.universitat_autonoma_de_barcelona_geology_mineralogy.minescope.Settings.saveToExternalStorage(Settings.java:219)
    at com.universitat_autonoma_de_barcelona_geology_mineralogy.minescope.Settings.access$100(Settings.java:39)
    at com.universitat_autonoma_de_barcelona_geology_mineralogy.minescope.Settings$3.run(Settings.java:120)
    at java.lang.Thread.run(Thread.java:923)

How can I save the photos in the sdcard?

0

There are 0 answers