Skip to content

4. Picking Files

Kumar Bibek edited this page Mar 1, 2016 · 4 revisions

Picking files

Use FilePicker to pick files from your device. You can choose single or multiple files from your device.

It is mandatory to set a FilePickerCallback before triggering the pickFile(); method, or an exception will be raised.

FilePicker filePicker = new FilePicker(Activity.this);
// filePicker.allowMultiple();
// filePicker.
filePicker.setFilePickerCallback(new FilePickerCallback() {
    @Override
    public void onFilesChosen(List<ChosenFile> files) {
        // Display Files
    }

    @Override
    public void onError(String message) {
        // Handle errors
    }
});

filePicker.pickFile();

After this call, you need to submit the onActivityResult(int requestCode, int resultCode, Intent data) to FilePicker so that the processing might start.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Picker.PICK_FILE && resultCode == RESULT_OK) {
        filePicker.submit(data);
    }
}

The FilePickerCallback will be triggered once the file has been processed.

The one thing you have to handle is when your Activity is killed when the user is still choosing a photo. In such a scenario, FilePicker reference will be destroyed since the Activity will be re-created. An additional check is required to handle this scenario. You just have to create a new FilePicker object, attach the callback and call the FilePicker.submit(data) method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Picker.PICK_FILE && resultCode == RESULT_OK) {
        if(filePicker == null) {
            filePicker = new FilePicker(Activity.this);
            filePicker.setFilePickerCallback(this);
        }
        filePicker.submit(data);
    }
}
Clone this wiki locally