hi i am new to android development. i manually kept a pdf file in emulator sdcard through ddms, and i also installed "adobe reader" in emulator when i tried to read the pdf file in emulator
with the following code
File file =
new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/iTunes Connect.pdf");
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(xv.this,
getString(R.string.app_name),
Toast.LENGTH_SHORT).show();
}
i am getting the file path is not valid error.
can any one help me in this.
use %20(for white space) in between iTunes and 20Connect.pdf.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/iTunes%20Connect.pdf");
I think this will solve your problem
try out this path
File file=new File("/sdcard/iTunes Connect.pdf");
I think this will work for u
I think you should not use hard coded file paths.
The framework will give you the base path of the area you want to save files to.
For SD card you should, use Environment.getExternalStorageDirectory()
local files you should, use Context.getFilesDir() (or Context.openFileOutput(String name, int mode), etc)
local cache you should, use Context.getCacheDir()
For emulator you can try File file=new File("mnt/sdcard/iTunes Connect.pdf");
I think that your emulator have not adob reader install please check first it is install or not
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
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
} `enter code here`
Related
I am having an issue, I have never had problem opening files via ACTION_VIEW the next way:
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
String dataType = "image/*";
if (file.exists()) {
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
fileIntent.setDataAndType(Uri.fromFile(file), dataType);
fileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(fileIntent, "Open file");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is a problem when opening the file");
}
} else {
Toast.makeText(getContext(), "Invalido", Toast.LENGTH_LONG).show();
}
The problem I am having right now is that even though the file exists when I choose the app to open the file it immediately closes and tells me Not found. I have put the image I am loading in an image view and there is no problem, so the file is valid but for some reason it has conflicts when I am opening it via intent.
I am aware that it may have something to do with the way I am creating the file, I am retrieving it from Google drive so I am writing the file using the Apache Commons library the next way:
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
try {
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
What is it I am doing wrong? I am not totally sure if the problem has to do with the copy method executing asynchronously or something like that.
Thanks in advance.
I have never had problem opening files via ACTION_VIEW the next way
That code will never work, as third-party apps have no rights to work with files on getFilesDir() of your app.
What is it I am doing wrong?
You are attempting to serve an inaccessible file to third-party programs. Use FileProvider to serve the file, using FileProvider.getUriForFile() to get the Uri to use in your ACTION_VIEW Intent.
I have downloaded a file (133465.pdf) using the Download manager and now it is stored in the Downloads folder of the mobile phone (Internal storage).
How should i try and retrieve the downloaded pdf from the Downloads folder?
I am using the below code to try and retrieve the pdf from the downloads folder but i am getting an error on the Toast, saying "Cannot display PDF (133465.pdf cannot be opened)" .
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "133465.pdf";
Log.i("Fragmentadapter1", file);
File videoFile2Play = new File(file);
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "application/pdf");
imageContext.startActivity(i);
I don't know if i am using the right file location to access the file.
Any help or suggestion will be appreciated.
If you are working for Lollopop and Below: You don't have to ask the user for permission on run-time. The manifest Permissions will do.
If you are working for Marshmellow and up: You have to ask the user for permission on run-time and act according to the users output.
Remember: You still have to give the Permissions on the Manifest too.
To Download a PDF on users Downloads folder :
DownloadManager downloadmanager;
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
downloadmanager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
String url = hardcode + bb ;
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(bb )
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
bb)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Log.i("Download1", String.valueOf(request));
downloadmanager.enqueue(request);
Reference
To View the Downloaded PDF from the Downloads folder of the Users device:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator +
"YOUR FILE NAME");
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
}
Note: Make sure u get the permission granted before downloading the Viewing the PDF file for Marshmellow and UP.
I download a pdf file to internal storage and then programmatically create buttons that take them to an action view. I can listFiles[] and Toast that they are there but the pdf viewer says file does not exist or file can not be viewed.
These are the main components of the write to internal storage during download.
private File file;
file = new File(mContext.getFilesDir(), filename+".pdf");
// Output stream to write file in internal storage
OutputStream output = new BufferedOutputStream(new FileOutputStream(file));
Then in another activity I get the filenames from the database and create a table with buttons
// ....Inside a for loop .....
Button c3 = new Button(this);
c3.setText("view");
c3.setId(p.getPosterID());
c3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
File pdfFile = getBaseContext().getFileStreamPath(filename+".pdf");
if (pdfFile.exists()){
Uri path = Uri.fromFile(pdfFile);
//================================================================================
Log.d("path: ", path.toString());
//this will log: file:///data/data/com.myapp.posterviewer/files/5453b54b83b5f.pdf
//================================================================================
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}
catch(ActivityNotFoundException e){
Toast.makeText(ListPosters.this, "No Application Available", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(ListPosters.this, "The file does not exist", Toast.LENGTH_LONG).show();
}
}
});
Am I generating the path right with Uri path?
I am not able to see the files from windows explorer when in the app folder either.
But all my checks say file is exists and I thought that would be in the app root folder.
Internal Storage Only Visible to your Application. The OutSide Application(Pdf Viewer) Cannot Access it. Save you Pdf file in External Storage and then open it via Pdf Viewer
I have a string (called comments) that contains some text that I want to display using an external app. I initially create the file like so:
String end = "rtf";
FileOutputStream outputStream;
try {
outputStream = openFileOutput("document." + end, Context.MODE_PRIVATE);
outputStream.write(comments.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However I am unable to open the file with an external application when I try the following:
String type = "text/rtf";
Intent intent = new Intent (Intent.ACTION_VIEW);
File file = new File(getFilesDir() + "/document." + end);
Uri fileUri = Uri.fromFile(file);
intent.setDataAndType(fileUri,type);
startActivityForResult(intent, Intent.FLAG_GRANT_READ_URI_PERMISSION);
The message that I receive when I open try to the document with the external app is:
"open failed: EACCESS (Permission denied)."
Please advise. Thanks.
However I am unable to open the file with an external application when I try the following:
Correct. Intent.FLAG_GRANT_READ_URI_PERMISSION is for use with a ContentProvider, not for bare file:// Uri values, such as you are using. Use FileProvider to add such a ContentProvider to your app. See also the "Sharing Files" training module and this sample app.
Bear in mind that there's a good chance that your next problem will be an ActivityNotFoundException, as relatively few Android devices will have an app that will support the text/rtf MIME type.
I have made an app which downloads the pdf from the server and stores it in
/data/data/<package_name>files
using this code:
FileOutputStream fos = openFileOutput(pdfFileName, Context.MODE_WORLD_READABLE);
fos.write(pdfAsBytes);
fos.close();
But when reading these file from the pdf reader app which I already have on the device is sometimes showing black screen and sometimes displays the file with annoying fonts. The code I am using is:
File file = new File("/data/data/<package_Name>/files/pdffile");
Uri path = Uri.fromFile(file);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent);
}
catch(Exception e)
{
Log.e("Activity Not Found Exception",e.toString());
}
I have tried the same code with the same files at other path(in sdcard) they work fine.
Please help me and tell me what should have gone wrong.
What should be a possible way to correct it?
You should use method
android.content.Context.getFilesDir().
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
This code works for me:
File file = new File(this.getFilesDir(), pdfFileName);
Uri path = Uri.fromFile(file);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch(ActivityNotFoundException e) {
Log.e("Activity Not Found Exception",e.toString());
}
There are only 2 methods to achieve what you want:
1) Using SDCARD
You save downloaded pdf somewhere SDCARD. Something like this:
Instead of creating a file:
File pdfFile = new File(Environment.getExternalStorageDirectory(), "pdffile");
FileOutputStream fos = new FileOutputStream(pdfFile);
fos.write(pdfAsBytes);
fos.close();
...
And you use pdfFile when creating an Intent.
2) Using custom ContentProvider
The second method can be used if you still do not want to use your SDCARD storage. You can use your app's CacheDir (you will download your file there). This involves creating your own ContentProvider, and after that you will be able to pass corresponding URI to the pdfreader app.
Details on how to do this all are here.
There is no known other methods to open any downloaded file in 3rd party app in Android.