Brian S
Brian S

Reputation: 5056

Android: iteration over SD card directories causes hang

For my current project, I want a list of folders on the SD card which contain image files. My current code seems to work perfectly... but it causes the app to hang, bringing up the "[app] is not responding" window. If I tell the phone to wait for the app to respond, there's no issues, but I don't want to force such behavior on a user.

What can I do to avoid making my app hang during this process?

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.picker);

    Set<File> directoryEntries = new HashSet<File>();

    Stack<File> dirs = new Stack<File>();
    // FilenameFilter#accept(File, String): returns true if file is an image
    ImageFilter imagefilter = new ImageFilter();
    // FileFilter#accept(File): returns true of file is a directory
    DirectoryFilter dirfilter = new DirectoryFilter();

    dirs.push(Environment.getExternalStorageDirectory());
    while(!dirs.empty())
    {
        File currentDir = dirs.pop();
        File[] subdirs = currentDir.listFiles(dirfilter);
        File[] images = currentDir.listFiles(imagefilter);

        if(images != null && images.length > 0)
            directoryEntries.add(currentDir);

        for(File dir : subdirs)
            dirs.push(dir);
    }
}

Upvotes: 0

Views: 330

Answers (1)

Blackbelt
Blackbelt

Reputation: 157487

you are experience an ANR - application not responding - because the operation you are performing are heavyweight. Use a thread for heavyweight operation or an AsyncTask. Read the Painless thread guide by android.

Upvotes: 4

Related Questions