user7028276 user7028276 - 10 months ago 91
Android Question

Getting one or more files from onActivityResult Intent, and their filenames?

I am using this code to allow the user to select multiple .csv files from their storage:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("text/comma-separated-values");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Get CSV Files"), REQUEST_IMPORT_CSV);


After choosing the files it goes to onActivityResult() and so far I have done:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_IMPORT_CSV:
if (data != null) {
ClipData clipData = data.getClipData();
ArrayList<Uri> csvUris = new ArrayList<>();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
clipData.getItemAt(i).getText()
csvUris.add(clipData.getItemAt(i).getUri());
}
}
else {
csvUris.add(data.getData());
}

}
break;
}
}



  1. Is this the right way to get all the relevant Uris from the result? If seems like if the user picks one file, I get the Uri from data.getData(), and if the user picked multiple files, then it goes straight to this clipData() thing instead.

  2. Assuming (1) is correct, how do I get the filenames of the corresponding files that the user chose? For example "chosen_file.csv" (I am not asking for the path).


Answer Source

Is this the right way to get all the relevant Uris from the result?

AFAIK, yes. Leastways, it has worked for me.

how do I get the filenames of the corresponding files that the user chose?

Strictly speaking, you don't. There is no requirement for the Uri to point to a file, any more than the URL to this Web page has to point to a file.

What you can do is wrap the Uri in a DocumentFile, via fromSingleUri(). Then, call getName() on the DocumentFile to get a "display name" for the content. Depending on where the user got the content from, this may be a filename-like value. It is supposed to be something user-recognizable. However, do not assume that it is a filename, as it could be something else.