Open pdf viewer from content uri at Android Q - android

I store the pdf file using this code:
val intent = Intent().apply {
action = Intent.ACTION_CREATE_DOCUMENT
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/pdf"
putExtra(Intent.EXTRA_TITLE, file.name)
}
startActivityForResult(intent, SAVE_FILE_REQUEST_CODE)
and after at onActivityResult Im saving data using OutputStream. Uri to file can look like:
content://com.android.providers.downloads.documents/document/4594
or
content://com.google.android.apps.docs.storage/document/documentId
But when im trying to start activity with this intent, pdf viewer app show error:
val openFileIntent = Intent(Intent.ACTION_VIEW, contentUri)
.apply {
setDataAndType(contentUri, "application/pdf")
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
}
Is it possible to open pdf viewer activity from content Uri?

I can confirm that the Comments have the answer: blackapps and Андрей Макаренко
val target = Intent(Intent.ACTION_VIEW)
target.setDataAndType(uri, "application/pdf")
target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
val intent: Intent = Intent.createChooser(target, "Open File")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
// Instruct the user to install a PDF reader here
}
Adding the "or Intent.FLAG_GRANT_READ_URI_PERMISSION" to the flags got my PDF reader to open the file correctly with the content:// Uri structure.

Related

How to open a file in another app via an Intent using an URI?

In my app, I have several file Uri (NOT URI) store. These are of the form:
content://com.android.providers.downloads.documents/document/427
My intention is, once I click a button, open one of these Uri in a file reader (may it be MS Word, Excel, PDF Reader... depending on the extension and device).
I am currently trying this snippet:
val file = File(Uri.parse(uri).path!!)
val myMime: MimeTypeMap = MimeTypeMap.getSingleton()
val newIntent = Intent(Intent.ACTION_VIEW)
val mimeType: String = myMime.getMimeTypeFromExtension(file.extension).toString()
newIntent.setDataAndType(
FileProvider.getUriForFile(applicationContext, "${applicationContext.packageName}.provider", file), mimeType)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
try {
startActivity(newIntent)
} catch (e: ActivityNotFoundException) {
}
But every time I try to open it, I get:
java.lang.IllegalArgumentException: Failed to find configured root that contains /document/427
Could you please tell me what am I missing? No answers I've found here targeted my problem. Thanks in advance!
UPDATE
Thanks to #CommonsWare help, I managed to avoid an Exception, my code now looks like this:
val newIntent = Intent(Intent.ACTION_VIEW)
newIntent.addCategory(Intent.CATEGORY_OPENABLE)
newIntent.data = Uri.parse(uri)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
try {
startActivity(newIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
}
I'm getting the Uri from here:
val fileResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
viewModel.uploadFile(result, false)
}
fileFab.setOnClickListener {
val intent = Intent()
intent.type = "application/*"
intent.action = Intent.ACTION_OPEN_DOCUMENT
fileResultLauncher.launch(intent)
}
Unfortunately, I'm getting a NoActivityFoundException
Get rid of:
val file = File(Uri.parse(uri).path!!)
...and replace your setDataAndType() call with:
newIntent.setDataAndType(Uri.parse(uri), mimeType)

how to load local file into webview

Im trying load this file into my webview but its not loading
file path is something like
/data/user/0/com.xyzapp.app/cache/temp_file.docx //this is getpathhh
below is my code
first activity:-
val browseintent = Intent(this, WebviewActivityNew::class.java)
browseintent.putExtra("url", "file://"+getpathhh.toString())
startActivity(browseintent)
second Activity:-
val url = intent.extras!!.getString("url")
webview_comp.getSettings().setLoadsImagesAutomatically(true);
webview_comp.getSettings().setJavaScriptEnabled(true);
webview_comp.getSettings().setAllowContentAccess(true);
webview_comp.getSettings().setAllowFileAccess(true);
webview_comp.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webview_comp.getSettings().setAppCachePath(url);
webview_comp.getSettings().setAppCacheEnabled(true);
webview_comp.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
url?.let { webview_comp.loadUrl(it) };
if i use Action_view
val pdfOpenintent = Intent(Intent.ACTION_VIEW)
pdfOpenintent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
pdfOpenintent.setDataAndType(Uri.fromFile(getpathhh), "*/*")
try {
startActivity(pdfOpenintent)
} catch (e: ActivityNotFoundException) {
}
im getting crash as 'E/UncaughtException: android.os.FileUriExposedException: file:///data/user/0/com.xyzapp.app/cache/temp_file.docx exposed beyond app through Intent.getData()'
following what i have tried
val pdfOpenintent = Intent(Intent.ACTION_VIEW)
pdfOpenintent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
pdfOpenintent.setDataAndType(
FileProvider.getUriForFile(
applicationContext,
"com.xyzapp.app.provider",
getpathhh
), "*/*")
try {
startActivity(pdfOpenintent)
} catch (e: ActivityNotFoundException) {
}
/data/user/0/com.xyzapp.app/cache/temp_file.docx
A WebView is for .html documents.
It cannot display a .docx file.

"The File is not supported" error for sharig a video using Whatsapp share

I am using the code to share in an Mp4 video in WhatsApp
private fun shareVideoToApp(context: Context, packageName: String) {
sharePath?.let { path ->
val file = File(path)
startActivity(Intent().apply {
action = Intent.ACTION_SEND
setPackage(packageName)
putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, context.packageName + ".provider", file))
type = "video/*"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
})
} ?: run {
Log.e(TAG, "Path is null")
}
}
The share path variable has value
/storage/emulated/0/Android/data/com.sample.androidapp/files/Download/VideoSnippets/1632536010_0_9265.mp4
Sharing is pretty messed up after fileproviders and newer android versions
Try androidx sharecompat lib which is already included if u use androidx
new ShareCompat
.IntentBuilder(context)
.setType("video/*")
.setStream(uri)
.setText("Desired text to share")
.startChooser();

error exposed beyond app through Intent, open pdf file

Through base64 string iam creating a pdf file.
This pdf file is succesfully created and stored in data/users/0/cache
On a button click i want to show this pdf file.
Function in kotlin:
fun decodeArbeidscontractString() {
var fos: FileOutputStream? = null
try {
f = File(context?.cacheDir, "newPdf_f.pdf")
f!!.createNewFile()
fos = FileOutputStream(f)
val decodedString: ByteArray = Base64.decode(pdf_string_arbeidscontract,
Base64.DEFAULT)
fos.write(decodedString) //write the base64 to the pdf
fos.flush()
fos.close()
val path: Uri = Uri.fromFile(f)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(path, "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
}
}
I can see the file in the emulator but cannot open it. How can i do that

Kotlin - How can open a csv file via Intent using default apps?

My android app flow is as follows:
Creates a csv file.
Store it in the default app folder.
Generates a notification of succesful creation
Open the csv in the default app.
I can not be able to open the csv via Intent or other methods so far.
With the following code I'm able to open the explorer but not in the folder path.
var path = this.applicationContext.getExternalFilesDir(null)?.absolutePath.toString()
println("Hey my path is $path")
val csvWriter = CSVWriter(
fileWriter,
CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END
)
csvWriter.writeAll(data.toMutableList())
csvWriter.close()
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/*"
}
startActivityForResult(intent, 2)
Also, I tried to develop a function but without effective response:
fun open_file(filename: String?) {
val path = File(filesDir, "dl")
val file = File(path, filename)
// Get URI and MIME type of file
val uri = FileProvider.getUriForFile(this, "$PACKAGE_NAME.fileprovider", file)
val mime = contentResolver.getType(uri)
// Open file with user selected app
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(uri, mime)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
}
I saw some possible solutions developed in java but there are deprecated and / or does not work converted in Kotlin.
Edit:
Given the suggestion of #CommonsWare, I'm trying to save the file in the path given but the user. However, I get the error : No Activity found to handle Intent
val FILE_EXPORT_REQUEST_CODE = 12
val exportIntent = Intent(Intent.ACTION_CREATE_DOCUMENT)
exportIntent.addCategory(Intent.CATEGORY_OPENABLE)
exportIntent.type = "text/csv"
val uri = Uri.parse("$path/file.csv")
exportIntent.data = uri
val filename = "file.csv"
exportIntent.putExtra(Intent.EXTRA_TITLE, filename)
startActivityForResult(exportIntent, FILE_EXPORT_REQUEST_CODE)
Thanks in advance.

Categories

Resources