My code with all necessary permissions does not create a folder on android 10 (Writes: "Failed to create folder"). What could be causing this? Help me please - don't really understand the error in my code.
Activity (if you need the rest of the code, I can throw it off):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (hasPermissions()){
makeFolder();
}
else {
method for requesting permission to work with files from the user();
}
});
}
private void makeFolder(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Folder");
if (!file.exists()){
Boolean ff = file.mkdir();
if (ff){
Toast.makeText(MainActivity.this, "Folder created successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Failed to create folder", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(MainActivity.this, "Folder already exist", Toast.LENGTH_SHORT).show();
}
}
Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Let's make it simple. This is the method call to create the folder:
makeFolder ( getFolderPath() );
The method to get the folder path:
public String getFolderPath()
{
String path = new File(Environment.getExternalStorageDirectory() + "/New Folder").getPath();
return path;
}
Now the main method that creates the folder:
private void makeFolder(String folderPath)
{
File file = new File(folderPath);
if (!file.exists()) {
file.mkdir();
Log.i("Folder path: " , " " + folderPath );
} else {
Log.e("Folder not created" , "Already exists!")
}
}
Replace file.mkdir()
with file.mkdirs()
and this should solve your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.