title: Lollipop and sd-card
body: <p>I am trying to create a file on sd-card on lollipop device. I am aware of ACTION_OPEN_DOCUMENT_TREE, and how to get permission for root of sd card. </p>
  
  <p>What I want to achieve is this:</p>
  
  <ul>
  <li>in my own folder browser, user picks a folder (on sdcard) where he wants file to be created (for example "/storage/emulated/0/a/b/c/d")</li>
  <li>first time this happens, I use <code>ACTION_OPEN_DOCUMENT_TREE</code>, and then in <code>onActivityResult</code> I use <code>findFile</code> to create file in correct location:</li>
  <li>next time user picks a folder on sd-card, he does not need to use <code>ACTION_OPEN_DOCUMENT_TREE</code> </li>
  </ul>
  
  <p>code:</p>
  
  <pre><code>public void test()
  {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, 1);
  }
  
  
  public void onActivityResult(int requestCode, int resultCode, Intent resultData) 
  {
    if (resultCode == RESULT_OK) 
    {
      Uri treeUri = resultData.getData();
  
      final int takeFlags = resultData.getFlags() &amp; Intent.FLAG_GRANT_READ_URI_PERMISSION;
      getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
  
  
      //assuming he picked "/storage/emulated/0/a/b/c/d"
      DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
      DocumentFile a = pickedDir.findFile("a");
      DocumentFile b = a.findFile("b");
      DocumentFile c = b.findFile("c");
      DocumentFile d = c.findFile("d");
  
      DocumentFile newFile = d.createFile("text/plain", "somefile.txt");
      OutputStream out;
      try
      {
        out = getContentResolver().openOutputStream(newFile.getUri());
        out.write("A long time ago...".getBytes());
        out.close();
      }
      catch (FileNotFoundException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (IOException e)
      {
        // TODO Auto-generated catch block
          e.printStackTrace();
      }
    }
  }
  </code></pre>
  
  <p>The question is how do I know in <code>onActivityResult</code> that user actually picked root of sdcard? He could have picked <code>/storage/emulated/0/a1/a2</code>, and if that folder has subfolders <code>a/b/c/d</code>, I would create file in wrong folder (because <code>findFile("a");findFile("b"); etc..</code> would also succeed).</p>
  
  <p>Also, next time user picks a folder (with my own folder picker), I get <code>path</code>, not <code>Uri</code>, how do I translate that <code>path</code> to <code>Uri</code> which can be used with <code>DocumentFile</code>?</p>