jam jam - 2 months ago 24
Java Question

Android: issue creating directory

I'm trying to create a directory inside the gallery folder (to store videos and photos nothing more), I tried this code:

File dir = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM + "/dirname");
dir.makedirs() ;


The problem is when I browse the SD card files and folders using the file manager everything is OK and the file does exist, but when I open my gallery there is no dir called dirname. What is the problem?

Thanks :-)

Answer

Here is my function that take a bitmap and save it in a directory ...

 public void saveBitmap(Bitmap bitmap) {

    if (createDirIfNotExists("TestApp")) {
        String filePath = Environment.getExternalStorageDirectory()
                + File.separator + "TestApp/TestSC" + date_value + "_" + time_value + ".png";
        File imagePath = new File(filePath);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
        } catch (FileNotFoundException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.problemOccured));
            Log.e("error", e.getMessage(), e);
        } catch (IOException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.problemOccured));
            Log.e("error", e.getMessage(), e);
        }
    } else {
        String filePath = Environment.getExternalStorageDirectory()
                + File.separator + "Pictures/TestSC" + date_value + "_" + time_value + ".png";
        File imagePath = new File(filePath);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
        } catch (FileNotFoundException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
            Log.e("error", e.getMessage(), e);
        } catch (IOException e) {
            hideLoadingDialog();
            showAlert(getString(R.string.successfullySavedPic));
            Log.e("error", e.getMessage(), e);
        }
    }


}

createDirIfNotExist() :

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}
Comments