Search code examples
androidfilechooser

Android file chooser not giving proper uri


I am trying to upload selected file. but when I select the file from recent file section I am getting different path like

content://com.android.providers.media.documents/document/document%3A1000007352

this.

I want path as below:

/storage/emulated/0/Download/template.xlsx

but I always want exact path where file is stored. I get proper path if I go in folders and select that file but I want to select file from recent section


Solution

  • I tired few ways to get real path but I failed. so I tried different approach:

    1. after getting uri, I checked if file has extension.

      val file = File(uri.getPath())
      if(file?.extension == ""){
        //file has no extension      
      }
      
    2. If file has no extension, then get file name as below

      val returnCursor = context.contentResolver.query(uri, null, null, null, null)
      if (returnCursor != null) {
          val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
          returnCursor.moveToFirst()
          filename = returnCursor.getString(nameIndex)
          returnCursor.close()
      }
      
    3. then save file temporarily in internal file storage using uri and display name

      val inputStream = AppApplicationClass.context.contentResolver.openInputStream(data)
      val header = inputStream!!.getBytes()
      val fos = FileOutputStream(file)
      fos.write(header)
      fos.close()
      
    4. after sending temporarily saved file to api, delete temp file

      fun deleteFile(file: File) {
          if (file.exists()) {
              if (file.delete()) {
                  printInDebug("file Deleted :" + file.path);
              } else {
                  printInDebug("file not Deleted :" + file.path);
              }
          }
      }
      

    p.s. this is an alternative way I found and it worked perfect for my situation, although your welcome to give answer to the question.