Error while reading pdf using MODE_WORLD_READABLE? - android

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.

Related

[Android ]Intent.ACTION_VIEW - Not found

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 am downloading pdf's to internal storage but my pdf viewer can not find them

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

How to open Context.MODE_PRIVATE files with external apps

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.

How to open a pdf file in android emulator from sdcard

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`

How to set up intent for viewing image that is saved in internal storage with default Android viewer?

What I am trying to do is to download image from web (its in GIF format, if that changes anything) and show it on screen with zoom/pan capability. I've successfully downloaded image into Bitmap instance myBitmap, but ImageView doesnt have zooming feature. So instead I'm willing to present it with default viewer which has zoom/pan features. In order to set up intent I need to provide URI to saved file.
So first I save file into internal storage (also giving access to other apps withe MODE_WORLD_READABLE):
try {
FileOutputStream out = openFileOutput("scrible",
Context.MODE_WORLD_READABLE);
myBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (FileNotFoundException e) {
Log.d(myTag, e.toString());
}
Then I successfully check its really readable:
File myFile = new File(getFilesDir(), "scrible");
if (myFile.canRead()) {
Log.d(myTag, "Its readable");
}
Then I try to set up intent (which gives me error: stopped unexpectedly):
Uri fileUri = Uri.fromFile(myFile);
startActivity(new Intent(Intent.ACTION_VIEW, fileUri));
I've tried to set up intent separately and it doesnt give error antil call to startActivity(intent);
What I am doing wrong?
The following works well for me:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(outputFileName)),"image/jpeg");
startActivity(intent);
The difference that I see is that you do not call the setDataAndType.

Categories

Resources