I'm working on a gallery app which displays all the images in a phone or a pen-drive. I successfully managed to list all the images and displays it into the app. But I think it is pretty slow. I'm using Depth First Search technique inside an AsyncTask. So is there any other method which can be used inside AsyncTask which is much faster.
Here root is a DocumentFile which is made from a tree URI.
Here is the code I've used.
public class ImageBackgroundTask extends AsyncTask<Object, Object, ArrayList<DocumentFile>> {
DocumentFile root;
ArrayList<DocumentFile> result;
ProgressDialog pg;
Context context;
private AsyncTaskCompleteListener<ArrayList<DocumentFile> > callback;
ImageBackgroundTask(DocumentFile root, Context context, AsyncTaskCompleteListener<ArrayList<DocumentFile>> cb){
this.context=context;
this.root=root;
this.callback = cb;
}
@Override
protected ArrayList<DocumentFile> doInBackground(Object... voids) {
Queue<DocumentFile> stack=new ArrayDeque<>();
ArrayList<DocumentFile> list=new ArrayList<>();
for(DocumentFile f:root.listFiles()){
stack.add(f);
}
while(!stack.isEmpty()){
DocumentFile child=stack.remove();
if(child.isDirectory()){
for(DocumentFile file:child.listFiles()){
stack.add(file);
}
}
else if(child.isFile()){
String name=child.getName();
if(name.endsWith(".jpg")
|| name.endsWith(".png")
|| name.endsWith("jpeg")
|| name.endsWith("JPG")
|| name.endsWith("JPEG")
|| name.endsWith("PNG"))
list.add(child);
}
}
return list;
}
@Override
protected void onPreExecute() {
pg=new ProgressDialog(context);
pg.setMessage("Loading...");
pg.show();
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(ArrayList<DocumentFile> aVoid) {
pg.dismiss();
result=aVoid;
callback.onTaskComplete(result);
}
Here is the output.