Android Create Folders in Internal Memory

Android create folders in Internal Memory

I used this to create folder/file in internal memory :

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.

How to make a folder in internal storage?

take a look at the answer at android-create-folders-in-internal-memory. I think they made a good example, if you are looking for a solution in java.

EDIT:
As pointed out by someone, i post the full example for easier understanding:

File folder = new File(Environment.getDataDirectory() + File.separator + "YOUR_FOLDER_NAME_HERE");
if (!folder.exists()) {
if(!folder.mkdirs()){
//DO SOME ERROR HANDLING HERE
}
}

Creating Folder in Internal memory

try the below

File mydir = context.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists())
{
mydir.mkdirs();
}

Android create folder in internal root directory

You should use getExternalStorageDirectory() and you should ask for write permissions to it.

But note getExternalStorageDirectory() was deprecated on android 29, that means you should use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDir() instead if you target a newer android version depending on the contents of your files.

And you should ask for write permissions on the manifest (for old android versions, Build.VERSION.SDK_INT < 23) and ask for them on run time (for newer android versions, Build.VERSION.SDK_INT >= 23)

To check if the user has granted permission of external storage:

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission granted");
//File write logic here
return true;
}

If the permission is not granted you should ask for it:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

and implement OnRequestPermissionResult to get the result callback.

All this info and more code can be found here https://developer.android.com/training/permissions/requesting

Can't create folder in internal storage

At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.

So try this code..

//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);

/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());


//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();

/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());

Creating directory in internal storage

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



Related Topics



Leave a reply



Submit