Issue
I'm making an app where you are able to select images or documents from storage and they are then displayed in a list kinda like Google Drive so you can choose one and it opens and you can view it. This list is implemented using a RecyclerView, and I store the uri and file type in a json in SharedPreferences. I get the content using:
val getFile = registerForActivityResult(
ActivityResultContracts.GetContent()
) {
if (it != null) {
val fileLink = FileLink()
fileLink.setUri(it.toString())
fileLink.setType(contentResolver.getType(it)!!)
fileLink.setName(getFileName(it)!!)
list.add(fileLink)
presenter.saveChangesToList(list)
adapter.notifyDataSetChanged()
}
}
And then I just call:
getFile.launch("image/*|application/pdf")
This didn't let me pick stuff from the internal storage (the files appeared grayed out) and it didn't actually filter the selectable files. It worked perfectly with images taken with the camera though. To fix the "not being able to pick stuff from storage" I changed GetContent() to OpenDocument():
val getFile = registerForActivityResult(
ActivityResultContracts.OpenDocument()
) {
if (it != null) {
val fileLink = FileLink()
fileLink.setUri(it.toString())
fileLink.setType(contentResolver.getType(it)!!)
fileLink.setName(getFileName(it)!!)
list.add(fileLink)
presenter.saveChangesToList(list)
adapter.notifyDataSetChanged()
}
}
And then I call:
getFile.launch(
arrayOf(
"application/pdf",
"image/*"
)
)
With this, I am able to select files from storage and it also lets me restrict so you can only pick either images or pdfs. My problem now is that, if I get stuff like this, I can open the document once. If I close my app and open it again and try to open the document again, I get this error:
java.lang.SecurityException: UID 10156 does not have permission to content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FNewPdf
I open the documents using this code:
viewHolder.itemView.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(
Uri.parse(fileList[position].getUri().toString()),
fileList[position].getType()
)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(intent)
}
Could I get some help with this? I'm guessing it has to do with the permission to read uris, but I have no idea how to fix it. I also don't understand why I can open the files correctly the first time, but not after I restart the app.
Solution
You did not call takePersistableUriPermission()
on a ContentResolver
as soon as you were handed the Uri
to the selected content.
As a result, your rights to access the content will expire — your rights to access the content will be limited to the one activity instance that received the Uri
, not other activities or future app processes.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.