Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filenames for results returned from ActivityResultContracts.OpenMultipleDocuments() contract

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?

like image 676
Kenny Wyland Avatar asked Dec 23 '25 02:12

Kenny Wyland


1 Answers

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("*/*")
        }
    }
like image 96
Clyde Avatar answered Dec 24 '25 19:12

Clyde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!