views:

284

answers:

2

Can someone write me a complete choose file dialog? Maybe one where you can filter out all files except for ones with specific extensions? The internet needs such an example. I have not found anything lightweight enough to implement easily into on of my projects. The only other options seem to being using OI FileManger's open intents, but that requires the user already having the file manager installed.

I would be extremely grateful if someone could write a Dialog that would allow the user to browse folders and select a file, and return the path.

+7  A: 

Well if you are temping me with rep :D You just need to override onCreateDialog in an activity.

    //In an Activity
private String[] mFileList;
private File mPath = new File(Enviroment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList(){
  try{
     mPath.mkdirs();
  }
  catch(SecurityException e){
     Log.e(TAG, "unable to write on the sd card " + e.toString());
  }
  if(mPath.exists()){
     FilenameFilter filter = new FilenameFilter(){
         public boolean accept(File dir, String filename){
             File sel = new File(dir, filename);
             return filename.contains(FTYPE) || sel.isDirectory();
         }
     };
     mFileList = mPath.list(filter);
  }
  else{
    mFileList= new String[0];
  }
}

  protected Dialog onCreateDialog(int id){
  Dialog dialog = null;
  AlertDialog.Builder builder = new Builder(this);

  switch(id){
  case DIALOG_LOAD_FILE:
   builder.setTitle("Choose your file");
   if(mFileList == null){
     Log.e(TAG, "Showing file picker before loading the file list");
     dialog = builder.create();
     return dialog;
   }
     builder.setItems(mFileList, new DialogInterface.OnClickListener(){
       public void onClick(DialogInterface dialog, int which){
          mChosenFile = mFileList[which];
          //you can do stuff with the file here too
       }
      });
  break;
  }
  dialog = builder.show();
  return dialog;
 } 

Hope this helps!

schwiz
Add the ability to navigate folders and go up to parent folder, and you got it
Aymon Fournier
If you can't modify the above to navigate the filesystem, I don't know how you're going to graft it into your app in the first place. When he's already bent the "rules" and written the code for you, I sure hope you're not really going to hold the bounty ransom for that.
Blumer
I edited the code above to show how to include the folders. You should be able to figure out the rest. If you detect that the file pressed is a directory in onClick just set the new path and call onCreateDialog again.
schwiz