In this case I have to sort hundreds of DocumentFile objects using this method:
DocumentFile[] files = documentFile.listFiles();
ArrayList<DocumentFile> docFiles = new ArrayList<DocumentFile>();
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((DocumentFile)o1).lastModified() < ((DocumentFile)o2).lastModified()) {
return -1;
} else if (((DocumentFile)o1).lastModified() > ((DocumentFile)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
if (files != null) {
for (DocumentFile file : files) {
if (!docFiles.contains(file))
docFiles.add(file);
}
However, this takes way too long, about a MINUTE with 200 DocumentFile objects. I cannot understand this kind of vital class is so slow. It will have to be used more with the recent scoped storage changes.
Anyone have an idea how to get this sorting process done faster?
Many — perhaps most — of the methods on DocumentFile
wind up making requests of a ContentProvider
. Such requests are not cheap. And lastModified()
is such a method. Sorting 200 objects will result in thousands of these calls, and that is why it is taking a long time.
What you can do is:
DocumentFile
that holds the DocumentFile
plus a cached copy of lastModified()
DocumentFile
objects, so you make one lastModified()
call per DocumentFile
lastModified()
value in the Comparator
Making 200 lastModified()
calls is not going to be fast, but it will be faster than making thousands of those calls.