I am looping a method which returns DocumentFile for 100 or even more times . Many times the method returns null while it has already been looped for around 35 times.
This is the method which is being looped.
public static DocumentFile documentfile(final File file ) {
for (UriPermission permissionUri :con.getContentResolver().getPersistedUriPermissions()) {
DocumentFile rootDocFile = DocumentFile.fromTreeUri(con, permissionUri.getUri());
String[] parts = (file.getPath()).split("\\/");
for (int i = 3; i < parts.length; i++) {
if (rootDocFile != null)
{
rootDocFile = rootDocFile.findFile(parts[i]);
}
else {
rootDocFile = DocumentFile.fromTreeUri(con,permissionUri.getUri() );
rootDocFile = rootDocFile.findFile(parts[i]);
}
}
return rootDocFile;
}
return null;
}
This is how I am looping the method
for(int i=0;i<size;i++)
{
documentfile(file).createFile(mime, name)
}
All the above code is being executed inside an Async Task.
Any help would be really Grateful.
EDIT: Tried with the Updated code but still received the same error.
Updated Code
public static DocumentFile DocumentFile(final File file)
{
DocumentFile rootDocFile = DocumentFile.fromTreeUri(con, permission().getUri());
String[] parts = (file.getPath()).split("\\/");
for (int i = 3; i < parts.length; i++)
{
rootDocFile = rootDocFile.findFile(parts[i]);
}
return rootDocFile;
}
public static UriPermission permission()
{
for (UriPermission permissionUri : con.getContentResolver().getPersistedUriPermissions())
{
final File uri_path = new File(FileUtil.getFullPathFromTreeUri(permissionUri.getUri(), con));
if (uri_path.getName().toLowerCase().equals(new File("SD_CARD_PATH").getName().toLowerCase()))
{
return permissionUri;
}
}
return null;
}
This is how I am checking if the permission granted is for SD Card or not
public static boolean wrong_directory_selected(Uri uri, Context con)
{
final File uri_path=new File(FileUtil.getFullPathFromTreeUri(uri,con));
if(uri_path.getName().toLowerCase().equals(new File("SD CARD PATH").getName().toLowerCase()))
{
return false;
}
return true;
}