@ NonNull @ Override public Loader < SortedList < File > > getLoader ( ) { return new AsyncTaskLoader < SortedList < File > > ( getActivity ( ) ) { FileObserver fileObserver ; @ Override public SortedList < File > loadInBackground ( ) { File [ ] listFiles = mCurrentPath . listFiles ( ) ; final int initCap = listFiles == null ? 0 : listFiles . length ; SortedList < File > files = new SortedList <> ( File . class , new SortedListAdapterCallback < File > ( getDummyAdapter ( ) ) { @ Override public int compare ( File lhs , File rhs ) { return compareFiles ( lhs , rhs ) ; } @ Override public boolean areContentsTheSame ( File file , File file2 ) { return file . getAbsolutePath ( ) . equals ( file2 . getAbsolutePath ( ) ) && ( file . isFile ( ) == file2 . isFile ( ) ) ; } @ Override public boolean areItemsTheSame ( File file , File file2 ) { return areContentsTheSame ( file , file2 ) ; } } , initCap ) ; files . beginBatchedUpdates ( ) ; if ( listFiles != null ) { for ( java . io . File f : listFiles ) { if ( isItemVisible ( f ) ) { files . add ( f ) ; } } } files . endBatchedUpdates ( ) ; return files ; } /** * Handles a request to start the Loader. */ @ Override protected void onStartLoading ( ) { super . onStartLoading ( ) ; // handle if directory does not exist. Fall back to root. if ( mCurrentPath == null || ! mCurrentPath . isDirectory ( ) ) { mCurrentPath = getRoot ( ) ; } // Start watching for changes fileObserver = new FileObserver ( mCurrentPath . getPath ( ) , FileObserver . CREATE | FileObserver . DELETE | FileObserver . MOVED_FROM | FileObserver . MOVED_TO ) { @ Override public void onEvent ( int event , String path ) { // Reload onContentChanged ( ) ; } } ; fileObserver . startWatching ( ) ; forceLoad ( ) ; } /** * Handles a request to completely reset the Loader. */ @ Override protected void onReset ( ) { super . onReset ( ) ; // Stop watching if ( fileObserver != null ) { fileObserver . stopWatching ( ) ; fileObserver = null ; } } } ; }
Get a loader that lists the Files in the current path and monitors changes .