Mr.Adam
Mr.Adam

Reputation: 294

Android Recursive File Search

Can someone please point out whats going wrong here:

The code below loops through the directories on the /sdcard. If it finds a file it adds the name etc to an array. If it finds a directory, it drops in and scans it.

The system.out returns all of the files on the /sdcard.

The array adapter only lists what it finds at the top level directory

On my sd card I am expecting it to return two mp3 files, one in the top level directory, one burried within the tree. The system.out line finds both.

I suspect that the fls arraylist is being destroyed. If it is, how do I go about preserving this?

Thanks in advance!

 public void fill(File f) {     
        File[]files = f.listFiles();
          List<Option>fls = new ArrayList<Option>();
          if (files != null) {
                for(File ff: files){
                    if(!ff.isDirectory())
                        {
                        /** Only Add MP3's to the list    */
                        String filename=ff.getName();
                        String ext = filename.substring(
                                    filename.lastIndexOf('.')+1, filename.length());
                                           if(ext.equals("MP3")||ext.equals("mp3")||ext.equals("Mp3")||ext.equals("mP3"))
                        fls.add(new Option(ff.getName(),"File Size: "+ff.length()/1048576 + "MB",ff.getAbsolutePath()));
                        System.out.println( ff.getName() );
                        }
                    else
                        fill(ff);
               }    
          }

        Collections.sort(fls);
        adapter = new FileArrayAdapter(getActivity(),R.layout.folder_view,fls);
        this.setListAdapter(adapter);   
        }

Upvotes: 0

Views: 2486

Answers (1)

Jug6ernaut
Jug6ernaut

Reputation: 8325

With the code as it is the arraylist will be recreated everytime you enter a new folder, you need to take the adapter code out of the function and have the fill function take the arraylist as a parameter so that each call will take the same arraylist.

ie.

List<Option>fls = new ArrayList<Option>();

fill(f,fls);

Collections.sort(fls);
adapter = new FileArrayAdapter(getActivity(),R.layout.folder_view,fls);
this.setListAdapter(adapter); 

if you want to keep it down to one call(which i dont recommend), you can do

fill(f,null);

and in the fill function check if the arraylist is null, if it is initialize it, but you must still pass it to additional calls.

Upvotes: 1

Related Questions