Android: Directory and file chooser android library

Prashant picture Prashant · Mar 24, 2014 · Viewed 14.1k times · Source

I'm using aFileChooser android library project in my app to select the file from external storage. but it doesn't seem to pick only directory to let user select the download location to download the files. Is there any android library project which support both pick file and pick directory?

I understand there are multiple questions have been answered here either for file chooser or directory chooser but after extensive search I couldn't find one for both directory and file chooser. Any help would be appreciated.

Answer

DeGoosseZ picture DeGoosseZ · Mar 24, 2014

I have no android library project, but you can simply make your own file chooser with the next code. This code will ask you to chose a file browser, when you select a file in the file browser you'll get the path in the onActivityResult function in the FilePath String.

Create this public:

private static final int ACTIVITY_CHOOSE_FILE = 3;

When a button is clicked you can call this:

            Intent chooseFile;
            Intent intent;
            chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
            chooseFile.setType("file/*");
            intent = Intent.createChooser(chooseFile, "Choose a file");
            startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);

You can catch the directory with this code :

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;
        String path     = "";
        if(requestCode == ACTIVITY_CHOOSE_FILE)
        {
              Uri uri = data.getData();
              String FilePath = getRealPathFromURI(uri);

        }
    }

public String getRealPathFromURI(Uri contentUri) {
    String [] proj      = {MediaStore.Images.Media.DATA};
    Cursor cursor       = getContentResolver().query( contentUri, proj, null, null,null); 
    if (cursor == null) return null; 
    int column_index    = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Edit: If you do not want to use an external file browser, you can import this android library into your project: https://code.google.com/p/afiledialog/