Allow User To Select Path For Save File in Android

Vickyexpert picture Vickyexpert · Sep 13, 2016 · Viewed 9.6k times · Source

I am developing one application for our client and there is one little functionality where we are stuck, so need your help,

Scenarion: We have developed one recycle view, from where users can see list of images and songs and videos as per category, now User have one option to see or listen images, audio or video, and also there is another option to download it.

Need Help @ We have done this with one static path where user can save all files, but our client wants to allow users to select path to save files and for that we need file dialog from where user can select location.

Note: Guys note that for one static path we have done this and it is working superb, also we are storing that path in local database so we can use it later, So now just remain is how can we allow user to select location for save file?

Answer

prakash ubhadiya picture prakash ubhadiya · Sep 13, 2016

i think Android DirectoryChooser is help you for choose directory for file save.

Manifest

You need to declare the DirectoryChooserActivity and request the android.permission.WRITE_EXTERNAL_STORAGE permission.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
<application>
    <activity android:name="net.rdrei.android.dirchooser.DirectoryChooserActivity" />
</application>

Activity

To choose a directory, start the activity from your app logic:

 final Intent chooserIntent = new Intent(this, DirectoryChooserActivity.class);

    final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
            .newDirectoryName("DirChooserSample")
            .allowReadOnlyDirectory(true)
            .allowNewDirectoryNameModification(true)
            .build();

    chooserIntent.putExtra(DirectoryChooserActivity.EXTRA_CONFIG, config);

// REQUEST_DIRECTORY is a constant integer to identify the request, e.g. 0
startActivityForResult(chooserIntent, REQUEST_DIRECTORY);

Handle the result in your onActivityResult method:

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

    if (requestCode == REQUEST_DIRECTORY) {
        if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
            handleDirectoryChoice(data
                .getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR));
        } else {
            // Nothing selected
        }
    }
}