How to read a pdf in android - android

I want to read a PDF file in android.
I placed my PDF files in the assets folder.
How can i read the PDF file from there?
PDF Reader Link
I have checked the above link but it does not work for me.
It gives me an error saying that the Activity was not found.
And I also want to open a PDF file in WebView. So is it possible to read PDF in WebView?

u can download PDFbox API to read PDF in android
try this link: http://pdfbox.apache.org/

You need to have a application which can support that mimetype and open it.
In your device/emulator that app is not installed so it is throwing error

Another great solution to read pdf using externally installed application like Adobe Reader.
private void openPDF(final String pathToPDF) {
File file = new File(pathToPDF);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

Google cached displays formats like pdf, ppt, docx, etc. And you don't need to install any application at all.
Search the link in google and go to Cached.

private void openPDF(final String path) {
File file = new File(path);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

Related

How to open excel, doc files with intent from my app in MS-Excel or MS-Word - Android

My requirement is to download and view the Excel, Doc files in my app. So I downloaded the Excel/Doc file in phone storage and called the ACTION_VIEW Intent by passing the file path. Then I got this error saying "Try saving the file on the device and then opening it."
I can be glad if any one can suggest me another alternatives as well to open excel or doc files. Please guys i have searched a lot for this so far i didn't find the solution and i am sure that i have used proper intent for opening files.
Where My Code:
Intent intentpdf = new Intent(Intent.ACTION_VIEW);
intentpdf.setDataAndType(Uri.parse(message), "application/msword");
intentpdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
mactivity.startActivity(intentpdf);
} catch (ActivityNotFoundException e) {
if (!mactivity.isFinishing())
Toast.makeText(mactivity, "Install MSWord Viewer.", Toast.LENGTH_LONG).show();
}
Intent intentpdf = new Intent(Intent.ACTION_VIEW);
intentpdf.setDataAndType(Uri.parse(message), "application/vnd.ms-excel");
intentpdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
mactivity.startActivity(intentpdf);
} catch (ActivityNotFoundException e) {
if (!mactivity.isFinishing())
Toast.makeText(mactivity, "Install Excel Viewer.", Toast.LENGTH_LONG).show();
}
You need the flags FLAG_ACTIVITY_NO_HISTORY,FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION.
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
I had this exact same problem and I fixed it. The problem is most likely with your ContentProvider/FileProvider implementation. My Excel sheet opened fine in Google Sheets but I got this error in MS Excel. The fix was to return the proper content type (via the getType() method) out of your provider. Returning the wrong content type will cause the error.
Try this code to see if it helps...and if it does, you can fully implement the routine for files of all types.
#Override
public String getType(Uri uri) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Good Luck!
Try get mime type from file
public String getMimeTypeByFile(String filePath) {
MimeTypeMap type = MimeTypeMap.getSingleton();
return type.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filePath));
}
nothing is worked for me to open the Doc,PPT,Excel files with intent at last I find a better solution , please check the code here
if(fileType.equalsIgnoreCase("doc") || fileType.equalsIgnoreCase("docx")) {
String str = "com.microsoft.office.word";
Uri pathe = Uri.fromFile(fileN);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(pathe, "application/msword");
PackageManager packageManager = activity.getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
activity.startActivity(intent.createChooser(intent, "Choose app to open document"));
}
else
{
//Launch PlayStore
try {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+str)));
} catch (android.content.ActivityNotFoundException n) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+str)));
}
}
Here is the result : check the screenshot

How to read/open PPT files in Android?

[This question may be duplicate, but i din't find what i am looking for]
[Read]How can we open files like ppt, doc, pps, rtf, etc. in Android?
I am having PPT files. In my app, i have a list view which display the PPT file list available in my private app folder. In click of particular file, i want to open corresponding PPT file for reading in my App.
The App which i am creating is just like collection of PPTs and reading them one by one.
Please provide any API/Example/Links.
You need to use other application to open your ppt files , Make sure that file location you are providing is accessible to other application. Try with following :
final Uri uri = Uri.fromFile(file);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if(list.size() > 0)
startActivity(context, intent);
Available application will be shown to user and user can choose application which can open.
private void openPPT(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-powerpoint");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

Android - No Activity found to handle Intent { act=android.intent.action.VIEW - Trying to open a PDF File

I searched a lot to find a solution , but still can't find any
I am trying to open a PDF file in my android application
Here is my code to do this :
try
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
Log.d("CheckingURI", uri.toString());
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
catch (Exception e)
{
Log.d("OpenPDFError", e.getMessage());
}
The Tomcat Log implies that there is no activity to handle the intent
09-19 19:55:02.938: D/CheckingURI(30483): file:///mnt/sdcard/pdf/Read.pdf
09-19 19:55:02.948: D/OpenPDFError(30483): No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/pdf/Read.pdf typ=application/pdf }
Is there any other way to do this or can i open the PDF file with another default PDF viewer? If yes, how?
Update :
the main problem was that i did not install a PDF viewer application on my emulator ...
Try this instead:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/pdf/Read.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
CAVEAT: The above method only work if you have a pre-installed PDF Viewer. If not, you need to install a PDF Viewer.
You just have to popup some sort of error msg to the user if no activity was found to launch the PDF (In the error dialog you can let the user know he needs some PDF app and send him to the Play Store), though i'd suggest using this piece of code instead of the genral exception catcher you're using:
try {
/* your code */
...
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
or you can use some PDF library, like this one.

Android: How to open a specific folder via Intent and show its content in a file browser?

I thought this would be easy but as it turns out unfortunately it's not.
What I have:
I have a folder called "myFolder" on my external storage (not sd card because it's a Nexus 4, but that should not be the problem). The folder contains some *.csv files.
What I want:
I want to write a method which does the following: Show a variety of apps (file browsers) from which I can pick one (see picture). After I click on it, the selected file browser should start and show me the content of "myFolder". No more no less.
My question:
How exactly do I do that? I think I came quite close with the following code, but no matter what I do - and I'm certain that there must be something I didn't get right yet - it always opens only the main folder from the external storage.
public void openFolder()
{
File file = new File(Environment.getExternalStorageDirectory(),
"myFolder");
Log.d("path", file.toString());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivity(intent);
}
This should help you:
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
Please, be sure that you have any file explorer app installed on your device.
EDIT: added a shantanu's recommendation from the comment.
LIBRARIES:
You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.
I finally got it working. This way only a few apps are shown by the chooser (Google Drive, Dropbox, Root Explorer, and Solid Explorer). It's working fine with the two explorers but not with Google Drive and Dropbox (I guess because they cannot access the external storage). The other MIME type like "*/*" is also possible.
public void openFolder(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "myFolder" + File.separator);
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}
Here is my answer
private fun openFolder() {
val location = "/storage/emulated/0/Download/";
val intent = Intent(Intent.ACTION_VIEW)
val myDir: Uri = FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", File(location))
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
intent.setDataAndType(myDir, DocumentsContract.Document.MIME_TYPE_DIR)
else intent.setDataAndType(myDir, "*/*")
if (intent.resolveActivityInfo(context.packageManager, 0) != null)
{
context.startActivity(intent)
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
CustomToast.toastIt(context,context.getString(R.string.there_is_no_file_explorer_app_present_text))
}
}
Here why I used FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
I tested on this device
Devices: Samsung SM-G950F (dreamltexx), Os API Level: 28
Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).
Thread is old but I needed this kind of feature in my application and I found a way to do it so I decided to post it if it can help anyone in my situation.
As our device fleet is composed only by Samsung Galaxy Tab 2, I just had to find the file explorer's package name, give the right path and I succeed open my file explorer where I wanted to. I wish I could use Intent.CATEGORY_APP_FILES but it is only available in API 29.
Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.sec.android.app.myfiles");
Uri uri = Uri.parse(rootPath);
if (intent != null) {
intent.setData(uri);
startActivity(intent);
}
As I said, it was easy for me because our clients have the same device but it may help others to find a workaround for their own situation.
this code will work with OI File Manager :
File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
Uri uri = Uri.fromFile(root);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
startActivityForResult(intent, 1);
you can get OI File manager here : http://www.openintents.org/en/filemanager
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);
Will open files app home screen
Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/csv");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
then you just need to add the response
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case 0: {
//what you want to do
//file = new File(uri.getPath());
}
}
}
You seem close.
I would try to set the URI like this :
String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");
startActivity(intent);
But it's not so different from what you have tried.
Tell us if it changes anything ?
Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.
File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
.getLastPathSegment();
final String filePath = fullfileName.
substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);
fullfileName:
/mnt/sdcard/Download_Manager_Farsi/preview.png
filePath:
/mnt/sdcard/Download_Manager_Farsi

Open PDF in Android

I would like to open a PDF file from my android application. I've searched how to do it in internet, and it seems very easy, but it doesn't work, at least in my mobile (Sony XPeria P).
File file = ....
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.fromFile (file));
intent.setType("application/pdf");
startActivity(intent);
When this code is executed, a window is opened asking to choose an application to show the PDF. When I choose the Adobe Reader, it's opened by no document is shown.
What I'm doing wrong?
Try this, Its working for me
//Method to open the pdf file in the PDF Viewer
public void OpenPDFFile() {
File pdfFile = new File(Environment.getExternalStorageDirectory(),"PdfFile.pdf");//File path
if (pdfFile.exists()) //Checking for the file is exist or not
{
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);//Staring the pdf viewer
}
}
The setType("application/pdf") function removes all the previous data.
If the targetSdkVersion >= 24 we need to use file provider to get the Uri. See this post for details: https://stackoverflow.com/a/38858040/8192914
So, the final code would look something like this:
Uri pathUri = FileProvider.getUriForFile(getBaseContext(), context.getApplicationContext().getPackageName() + ".provider", finalFile);
Intent pdfViewerIntent = new Intent(Intent.ACTION_VIEW);
pdfViewerIntent.setDataAndType(pathUri, "application/pdf");
pdfViewerIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
pdfViewerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(pdfViewerIntent);

Categories

Resources