How to view a PDF file - java

I can not read a pdf file with my program. The code is simple but, unfortunately it does not work. thank you in advance
String path =getActivity().getFilesDir()+"/test.pdf";
File file = new File(path);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent=Intent.createChooser(target,"Open File");
startActivity(intent);

Here is code on how to open that file (test.pdf) with an Intent chooser:
File file = new File(getActivity().getFilesDir()+"/test.pdf");
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Source

PdfRenderer support is added in Android 5.0
Below Android 5.0, you have to make a workaround
See this blog written by CommonsWare for viewing PDF

how to open pdf file click here for complete code
private void openRenderer(String filePath) {
File file = new File(filePath);
try {
mFileDescriptor = ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY);
mPdfRenderer = new PdfRenderer(mFileDescriptor);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

PDF file could not be accessed in samsung j6 but can accessible in other android phones

I am receving this error: The file could not be accessed check your connection or make the filename shorter when trying to open a PDF file with Samsung j6, but I am able to open the same file with other android phone like Tecno.
Below is the code that I am using to open a PDF file.
File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File pdfFile = new File(d, examID+".pdf");
Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(DocExamView.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}

how to open pdf from sdcard

Trying to open pdf file from download folder on device,
i save the name of file in firebase and now i want to check if the file is already found on device and then open it else download from firebase.
File file = new File(Environment.getExternalStorageDirectory() + "filename");
System.out.println(Environment.getExternalStorageDirectory());
///but when i print Environment.getExternalStorageDirectory() i get
///storage/emulated/0
if (file.exists()) {
System.out.println(file.getAbsoluteFile());
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target = Intent.createChooser(target, "Open File");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("file not found");
}
try this to get your file from download directory
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename);

FileUriEXposedException in Sharing screenshot of a layout

Hey i am trying to share the screen shot of a layout. it works very well in all very version which are less than Oreo, but when i am trying to share on Oreo it is giving FileUriExposedException. Please If anyone knows about this issue please solve it as soon as possible.
Here is my code
public Bitmap takeScreenshot() {
View rootView = (FrameLayout)findViewById(R.id.frame_layout).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagepath1 = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagepath1);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
try{
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
Uri uri = Uri.fromFile(imagepath1);
sharingIntent.setType("image/*");
String share_text = "*Create, Share, Download* Valentine Frames and spread love on this \nValentine\uD83D\uDE18\uD83D\uDE18 for free...." +
"\n*Download Now:-* https://play.google.com/store/apps/details?id=technoapps4.valentineframes2019";
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, share_text);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(sharingIntent, "Share via"));}
catch ( Exception e)
{
Toast.makeText(this, ""+e, Toast.LENGTH_SHORT).show();
}
AFAIK sharing files by sharing their paths is not allowed anymore since oreo. I got this issue some time ago.
My solution was to share the file content with a content-provider.

Creating and sending a file

I am trying to create file in internal storage and then send it via email in Android.
However, I still get file not found or similar errors.
Please, help!
String FILENAME = "TestFile.txt";
Sending file by button click
btnSendFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File gpxfile = getFile();
Uri path = Uri.fromFile(gpxfile);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
Context context = v.getContext();
String email = "MYEMAILHERE";
i.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "Text");
i.putExtra(Intent.EXTRA_STREAM, path);
context.startActivity(Intent.createChooser(i, context.getString("Sending...")));
}
});
}
Creating file in internal storage
private void createTestFile() {
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write("Your content".getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Get file function. Return File if file exists
private File getFile() {
return new File(getFilesDir() + "/" + FILENAME);
}
Maybe you need to make
Context.openFileOutput(FILENAME, Context.MODE_APPEND);
Instead of that one you used? I think someone had similiar problem over here: android what is wrong with openFileOutput?

Android PDF Load Timing

The requirements: ensure that the PDF document is deleted from the device after the user has left the PDF viewing screen
The problem: on certain devices (Samsung 4.4.2 and Samsung 4.1.2 for sure, but not Asus 4.2.1) only the first time that the PDF is requested after restarting the application an error message is displayed stating "This document cannot be opened". Thereafter the PDF will load normally. I'm thinking this is a timing issue due to processes that need to be started the first time, but are running after the first attempted load.
The code: note that createFile() is called first, then startActivityForIntentResult()
private File file;
private ArrayList<Uri> uriList = new ArrayList<Uri>();
private void createFile() {
int fileNameLength = pdfFileName[0].length();
String fileName = pdfFileName[0].substring(0, fileNameLength - 4) + DateTime.now();
String fileExtension = pdfFileName[0].substring(fileNameLength - 4, fileNameLength);
byte[] content = Base64.decodeBase64(pdfData[0].getBytes());
BufferedOutputStream outputStream = null;
try {
File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, fileName + fileExtension);
outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(content);
file.deleteOnExit();
uriList.add(Uri.fromFile(file));
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static int REQUEST_CODE = 1;
private Intent intent;
private void startActivityForIntentResult() {
if (file.exists()) {
Uri targetUri = uriList.get(0);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivityForResult(intent, REQUEST_CODE);
}
catch (ActivityNotFoundException e) {
toastTitle = "Error Displaying PDF";
toastMessage = "Please make sure you have an application for viewing PDFs installed on your device and try again.";
toast = new GenericCustomToast();
toast.show(toastTitle, toastMessage, QueryForPDF.this);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_CANCELED && requestCode == REQUEST_CODE) {
if(!file.delete()) {
file.delete();
}
}
searchAgain();
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(!file.delete()) {
file.delete();
}
searchAgain();
}
#Override
public void onStop() {
super.onStop();
if(!file.delete()) {
file.delete();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(!file.delete()) {
file.delete();
}
}
EDIT: I have also tried implementing a callback to be absolutely certain that createFile() has finished it's work. I even tried adding delays (of different time increments) as well as adding (the completely unnecessary) flags for Intent.FLAG_GRANT_READ_URI_PERMISSION, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION.
I still don't know why this works, but here's the solution in case anyone else runs into this issue:
It's the directory where the file is created. For some reason on the two Samsung devices there was something different in how the files were either accessed or created versus the Asus device. So File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp"); becomes File path = new File(getExternalCacheDir().getAbsolutePath()); and the problem goes away.

Categories

Resources