title: Android Kotlin Write File to 'Files' -> 'Documents' - How do I get a URI?
body: <p>I'm trying to write a file from my Android App with Kotlin.  I see the reference material on the android developer site. <a href="https://developer.android.com/training/data-storage/shared/documents-files#use-cases" rel="nofollow noreferrer">Android Developer - Access Documents...</a>.  I would like to use what Android is recommending.</p>
  <p>When I try and use the context to get the external directory URI, I only get an optional File rather than an URI.  As would be expected, I get an error because I'm trying to pass a File? to a URI parameter.</p>
  <p>Question is, how do I get the URI to the 'Files' app 'Documents' directory?  Alternatively, should I be using a different function call to write the file to 'File' -&gt; 'Documents'</p>
  <pre><code>compileSdkVersion 30
  buildToolsVersion '30.0.2'
  
  minSdkVersion 27
  targetSdkVersion 30
  </code></pre>
  <p>Function from android site.</p>
  <pre><code>val CREATE_FILE = 1
  
  private fun createFile(pickerInitialUri: Uri) {
      val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
          addCategory(Intent.CATEGORY_OPENABLE)
          type = &quot;application/csv&quot;
          putExtra(Intent.EXTRA_TITLE, &quot;myToyBox.csv&quot;)
  
          // Optionally, specify a URI for the directory that should be opened in
          // the system file picker before your app creates the document.
          // putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
      }
      startActivityForResult(intent, CREATE_FILE)
  }
  </code></pre>
  <p>My function call attempt</p>
  <pre><code>private fun downloadFile() {
      val uri = context?.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) // &lt;- returns a File? 
      createFile(uri)  // &lt;-- needs a URI
  }
  </code></pre>