Reputation: 3850
I am trying to create a folder on my sdcard using the following code but it fails. This is my code written in onCreate()
:
File test = new File(Environment.getExternalStorageDirectory(),"my_directory");
if(!test.exists())
{
try
{
if (test.mkdir())
{
Log.d("xxx", "directory created");
}
else
{
Log.d("xxx", "directory creation failed");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Log.d("xxx","directory already present");
}
When I run the above code does not give any exception it just prints the
directory creation failed
log.
I have also given the following permission,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am using Xiaomi Redmi note 3 and Android version is 6.0.1.
Upvotes: 1
Views: 2985
Reputation: 1251
Try this code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
//do your work
} else {
requestPermission();
}
}
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do your work
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
Upvotes: 5
Reputation: 45
I know it just for API 21 (couse i wanted the same at my app, till now i do not know how to get on the sdcard)
you also need this in your manifest!!
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Environment.getExternalStorageDirectory()
declares the internal storage.
the exact path is: storage/emulated/0
you get it with:
Log.i(TAG, "path is:" + Environment.getExternalStorageDirectory().toString());
Upvotes: 0