androidfilemkdirs

Creating directory in internal storage


I think that my smartphone is a dumbphone. Trying to create a folder and it seems that it just wont get created. I am running CyanogenMod and dont know if this make it goes nuts.

This is what I have been testing:

File folder = new File(getFilesDir() + "theFolder");
if(!folder.exists()){
folder.mkdir();
}

And also this approac:

File folder = getDir("theFolder",Context.MODE_PRIVATE);

Solution

  • This answer was old and I updated it. I included internal and external storage. I will explain it step by step.

    Step 1 ) You should declare appropriate Manifest.xml permissions; for our case these 2 is enough. Also this step required both pre 6.0 and after 6.0 versions :

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

    Step 2 ) In this step we will check permission for writing external storage then will do whatever we want.

    public static int STORAGE_WRITE_PERMISSION_BITMAP_SHARE =0x1;
    
    public Uri saveBitmapToFileForShare(File file,Uri uri){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
    
    //in this side of if we don't have permission 
    //so we can't do anything. just returning null and waiting user action
    
        requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
       "permission required for writing external storage bla bla ..."
                    REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
            return null;
        }else{
            //we have right about using external storage. do whatever u want.
            Uri returnUri=null;
            try{
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() ,uri);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
                returnUri=Uri.fromFile(file);
            }
            catch (IOException e){
                //can handle for io exceptions
            }
    
            return returnUri;
        }
    
    }
    

    Step 3 ) Handling permission rationale and showing dialog, please read comments for info

    /**
     * Requests given permission.
     * If the permission has been denied previously, a Dialog will prompt the user to grant the
     * permission, otherwise it is requested directly.
     */
    protected void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showAlertDialog("Permission required", rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(BasePermissionActivity.this,
                                    new String[]{permission}, requestCode);
                        }
                    }, getString(android.R.string.ok), null, getString(android.R.string.cancel));
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }
    
    /**
     * This method shows dialog with given title & content.
     * Also there is an option to pass onClickListener for positive & negative button.
     *
     * @param title                         - dialog title
     * @param message                       - dialog content
     * @param onPositiveButtonClickListener - listener for positive button
     * @param positiveText                  - positive button text
     * @param onNegativeButtonClickListener - listener for negative button
     * @param negativeText                  - negative button text
     */
    protected void showAlertDialog(@Nullable String title, @Nullable String message,
                                   @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                   @NonNull String positiveText,
                                   @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                   @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        mAlertDialog = builder.show();
    }
    

    Step 4 ) Getting permission result in Activity :

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case STORAGE_WRITE_PERMISSION_BITMAP_SHARE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    shareImage();
                }else if(grantResults[0]==PackageManager.PERMISSION_DENIED){
                    //this toast is calling when user press cancel. You can also use this logic on alertdialog's cancel listener too.
                    Toast.makeText(getApplicationContext(),"you denied permission but you need to give permission for sharing image. "),Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    

    Step 5 ) In case of using internal storage. You don't need to check runtime permissions for using internal storage.

    //this creates a png file in internal folder
    //the directory is like : ......data/sketches/my_sketch_437657436.png
    File mFileTemp = new File(getFilesDir() + File.separator
                    + "sketches"
                    , "my_sketch_"
                    + System.currentTimeMillis() + ".png");
            mFileTemp.getParentFile().mkdirs();
    

    You can read this page for information about runtime permissions : runtime permission requesting

    My advice : You can create an Activity which responsible of this permissions like BasePermissionActivity and declare methods @Step 3 in it. Then you can extend it and call your request permission where you want.

    Also I searched a bit and found the Github link of codes @Step 3 in case of you want to check : yalantis/ucrop/sample/BaseActivity.java