android creating folder in root directory of the application

+1 vote
asked Sep 13, 2017 by harinee-rr

i am creating a module like i gave an access to camera for capturing the image and captured image should be visible only through the application not in gallery nor in file manager.And i created it.But only in some mobile like Samsung Mi mobiles images are not visible but in one plus and Sony images are visible,why so,It is working in some mobiles and not in some mobiles

my code:

private void createDirectoryAndSaveFile(Bitmap imageToSave) {

    File direct = new File(getFilesDir() + "/CAT_IMG/");
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
    String fileName = "fav" + timeStamp + ".JPG";
    if (!direct.exists()) {
       // File wallpaperDirectory = new File("/CAT_IMG");
        direct.mkdir();
    }

    File file = new File(direct, fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        createDirectoryAndSaveFile(photo);
        Log.e("URI", data.getExtras().get("data") + "");

    }
}

2 Answers

0 votes
answered Sep 13, 2017 by pratik

You will need permissions, in AndroidManifest.xml

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

create directory:-

 File mydir = context.getDir("dirname", Context.MODE_PRIVATE);
    if (!mydir.exists())
    {
         mydir.mkdirs();
    }
0 votes
answered Sep 13, 2017 by sam

If you want to store your file in the app's root directory, you should create your directory inside the app's root directory using getExternalFilesDir like below:

File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (!storageDir.exists()) {
    storageDir.mkdirs();
}

And then put your image files inside the directory. Also don't forget to provide permissions in your AndroidManifest.xml to read and write the storage like below:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...