Search code examples
androidandroid-storagedocumentfile

Walking a DocumentFile tree


I'm trying to walk an Android DocumentFile tree recursively but I cannot get a list of files to be returned for a subfolder. When I attempt listFiles() on the folder URI, I get the list of root files returned each time.

Why is this not working?

package com.example.usbfoldertest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "USBFolderTest";
    private static final int RQS_OPEN_DOCUMENT_TREE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE){
            Uri uriTree = data.getData();
            Log.d(TAG, "WalkTree: " + uriTree.toString() );

            WalkTree( uriTree );
        }
        super.onActivityResult(requestCode,resultCode,data);
    }

    private void WalkTree( Uri uriTop ) {

        Log.d( TAG, "LoadFileList: " + uriTop.toString() );

        DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTop);
        DocumentFile files[]      = documentFile.listFiles();

        if( files == null ) {
            Log.d( TAG, "files is null in LoadFileList()" );
        } else {
            for( DocumentFile f : files ) {

                if( f.isDirectory() ) {

                    Log.d( TAG, "FOLDER: " + f.getName());

                    if( f.getName().toLowerCase().contains("lost.dir") ) {
                        Log.d( TAG, "IGNORE LOST.DIR");
                    } else {
                        // Recurse into the folder..
                        WalkTree( f.getUri() );
                    }

                } else {
                    Log.d( TAG, "FILE: " + f.getName());
                }
            }
        }
    }
}

Solution

  • It looks as though upgrading the documentfile library fixes the problem. I add this to my build.gradle and it works as expected now:

    implementation 'androidx.documentfile:documentfile:1.0.1'