In my Android app, I launch a document chooser so the user can import some documents into my app:
this.intentlauncherchoosedoc = this.registerForActivityResult(
new ActivityResultContracts.OpenMultipleDocuments(),
new ActivityResultCallback<List<Uri>>() {
@Override
public void onActivityResult(List<Uri> urilist) {
for (Uri uri : urilist) {
String filename = uri.getLastPathSegment();
createdoc(uri, filename);
}
}
}
);
Unfortunately, when the user choose a document, the uri that comes back looks like this:
content://com.google.android.apps.docs.storage/document/acc=1;doc=encoded=mgMyynWh7Lrq1qW1dradGc60EJWehheCQiS5mYY7a8CF80Ouzro=
Is there any way to get the original filename of the document that was chosen, so that I can save that filename and list it to my user when they are reviewing their imported docs?
For the benefit of others searching for this, here is sample Kotlin code to open a single file and retrieve its name and content. The use of GetContent() guarantees that the column DISPLAY_NAME will be included in the returned metadata.
private val getFile = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
requireActivity().contentResolver.apply {
query(uri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst()
cursor.getString(nameIndex)
}?.let { fileName ->
openInputStream(uri)?.use { stream ->
presenter.addFile(fileName, stream)
}
}
}
}
And to link it to a button:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.chooseFile).setOnClickListener {
getFile.launch("*/*")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With