I've searched for a while on the internet but I didnt find a solution!
In my project I put a PDF file inside the drawable folder (I dont know where else to put it, honestly). That PDF is a menù that shows the user all the food he can find in that restaurant.
There is a button that enables the user to open that PDF file. By clicking over it I receive a error message. More or less it says that the App cant file my file: "Impossibile to open menuristorante.pdf".
I created a method to open that file and this is the code I wrote:
public void openMenuRistorante(View view)
{
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/menuristorante.pdf");
Uri path = Uri.fromFile(pdfFile);
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(this, "Nessuna Applicazione per leggere i pdf", Toast.LENGTH_SHORT).show();
}
}
Probably I am wrong putting my file in the wrong directory.. But where have I to put it? Keep in mind that my PDF file must be already into the app, so it must be inside the phone when the user installs this App.
Thanks
Put the PDF file in the assets folder and try using the following code:
Uri file= Uri.parse("file:///android_asset/mypdf.pdf");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file.toString()));
try {
Intent i;
i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(file,mimeType);
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to view this file type",
Toast.LENGTH_SHORT).show();
}
I'm doing a similar thing in my app, I have my files though in the download folder of my mobile in a sub-folder called "Documents", I guess you could do the same, it's better than keeping it in drawable. here's the code I use :
try {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/Documents/" + fileName);
Intent intent = new Intent("com.adobe.reader");
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Documents.this, "Erreur d'ouverture du fichier", Toast.LENGTH_LONG).show();
}
Related
on a button click below function is executed , I gave it storage permission when prompted to. without the StartActivity line it's not crashing , can anyone help me with this , i want to open a specific existing file with device default pdf viewer. ther is no error with permissions or file existance or pdf viwer application presence.
public void openfile(View v) {
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
} else {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Zio app/" + "notes.pdf"); // -> filename = maven.pdf
if (pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(NewActivity.this, "No such file exists", Toast.LENGTH_SHORT).show();
}
}
}
I tried a lot of times , it didn't even shown a "no application found to view pdf " error
straightaway its crashing
finally I got the answer , now its working , Had to use FileProvider , now it's more like
if anyone facing same problem let me know I will post step by step solution
public void openfile(View v) {
if (!checkstoragepermission()) {
requestReadpermission();`
}else {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Zio
app/" + "/materials/"+"notes.pdf"); // -> filename = maven.pdf
if (pdfFile.exists()) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/"
+ "Zio app" ,"materials");
File newFile = new File(imagePath, "notes.pdf");
Uri path = FileProvider.getUriForFile(this,
"com.example.zio.fileprovider", newFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent intent = Intent.createChooser(pdfIntent, "Open File");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to
view PDF", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(NewActivity.this, "No such file exists",
Toast.LENGTH_SHORT).show();
}
}
}
I am developing an app for filling pdf forms, I am saving the pdf to the internal storage and then sharing it using the intent ACTION_CREATE_DOCUMENT. This intent returns a URI which i then copy my local pdf into.
All this works fine however the intent opens a file explorer popup so that the user can choose where to save the pdf, and here in lies the problem, when the user presses SAVE; the app creates a 0b file in that location (as it should), but then it reopens the file explorer prompting the user to SAVE again, this happens two or three times and then it finally close for real at which point the pdf data overwrites the latest of the now numerous 0b files.
public int WRITE_REQUEST_CODE=45;
...
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void buttonExport(View view) {
Toast.makeText(this, "Exporting - This will take around 1min", Toast.LENGTH_LONG).show();
// Template of PDF with acrofields (template.pdf).
// TRY to open the pdf stored in the raw res directory
// then convert it to a file object by copying it
try {
//
InputStream inputStream =null;
if (template.equals("crfminortemplate")){
inputStream = getResources().openRawResource(R.raw.crfminorpdftemplat);
}
else if (template.equals("crfmajortemplate")){
inputStream = getResources().openRawResource(R.raw.crfmajorpdftemplat);
}
File tempFile = new File(getFilesDir(),template);
//
copyFile(inputStream, new FileOutputStream(tempFile));
// Now Questions res is tempFile ..
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
try {
PDFManipulation.fillPDF(view, template, fileName, Answers);
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
Toast.makeText(this, "Export Complete - save to drive or email", Toast.LENGTH_LONG).show();
sharePDF(getFilesDir()+"/"+fileName+".pdf");
}
private void sharePDF(String PDFPPath) {
Uri path = FileProvider.getUriForFile(this, "com.example.cst_app_v3", new File(getFilesDir(),fileName+".pdf"));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Sent from CST App Android " + PDFPPath);
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("application/pdf");
startActivityForResult(shareIntent,0);
Intent saveIntent = new Intent();
saveIntent.setAction(Intent.ACTION_CREATE_DOCUMENT);
saveIntent.putExtra(Intent.EXTRA_TITLE,fileName+".pdf");
saveIntent.addCategory(Intent.CATEGORY_OPENABLE);
saveIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
saveIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
saveIntent.setType("application/pdf");
startActivityForResult(saveIntent,WRITE_REQUEST_CODE);
Intent chooserIntent = Intent.createChooser(shareIntent, "Share or Save ...");
Intent[]arrayofintent = {saveIntent};
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,arrayofintent);
startActivityForResult(chooserIntent,0);
startActivity(chooserIntent);
Log.d("Alert",path.getAuthority()+" "+ path.getPath());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK && requestCode == WRITE_REQUEST_CODE) {
//DO THE COPY PASTE FROM LOCAL to THE URI data
}
}
Again
I want the user to start the save intent and have the file selector popup once let the user name the file and choose the save location, press save and then return to my the my app where the pdf is copied to the location they specified
if anyone knows/has experienced this issue or thinks they know what might be happening it would be great to hear from you.
Every time you call startActivityForResult or startActivity it will start a new Activity.
So I count 4 of these in your example code but with only 2 calls that will actually return a result that would cause a file to be written.
To fix this just remove all the startActivityForResult or startActivity EXCEPT for the third one which you change to startActivityForResult(chooserIntent,WRITE_REQUEST_CODE);
This works (was tested) BUT provides a very bad UI experience as you have to know to select the Files App to save the document.
It would be much better to split these to different types of action in to separate menu items, Buttons, Floating Action Buttons, or however you getting the user to "Share or Save" as you can provide a better UI than the Intent chooser.
I'm developing a video converter in android studio. I'm able to convert file successfully and can play the resulting file with:
File file = new File(filepath);
Uri path = Uri.fromFile(file);
Intent Openintent = new Intent(Intent.ACTION_VIEW);
Openintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Openintent.setDataAndType(path, "audio/mp3");
try {
startActivity(Openintent);
}
catch (ActivityNotFoundException e) {
}
But I can't find any code to open the resulting folder and show converted file marked. Like we have in windows Locate file in folder.
here is how you can open the containing folder for the converted file
String folderPath = filepath.substring(0 , filepath.lastIndexOf('/') + 1);
Uri uri = Uri.parse(folderPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "resource/folder");
startActivity(intent);
I have the following code to launch application chooser to open any type of file, but when ever I try to open the file I get the message file cannot be opened.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(path));
if(type.contains("image")) {
intent.setDataAndType(Uri.parse(path),type);
}else if(extension.equalsIgnoreCase("txt")){
intent.setDataAndType(Uri.parse(path),"text/plain");
}else{
intent.setDataAndType(Uri.parse(path),type);
}
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intentOpen = Intent.createChooser(intent, "Open File");
try {
activity.startActivity(intentOpen);
} catch (ActivityNotFoundException e) {
}
any help will be appreciated, thanks in advance
I solved it, i had to add file:// at the start of the path to open the file.
path="file://"+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"/"+myFileName;
Hi I have the following code to share an image:
// Share
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
Uri uri = Uri.parse(getFilesDir() + File.separator + "myGoal.jpg");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
It works to share the image to Dropbox but if I pick the Facebook option, I get Facebook's status update dialog with no image attached and if I try to update my status with 'Test' it doesn't work. No errors. Just not working.
I know it's not the image because it uploads to my Dropbox properly and I can pull up the image and look at it.
Do I have to attach the image to the intent differently for it to work with Facebook?
Any ideas? I'm debugging on a physical device.
So I figured out the problem.
I was saving the picture to internal storage with getFilesDir() which put the picture into my apps sandbox and made inaccessible to the other apps.
I replaced my code with the following:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MyApp/";
File dir = new File(file_path);
dir.mkdirs();
File file = new File(dir, "myPic.png");
FileOutputStream fOut = new FileOutputStream(file);
screenshot.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
// Share
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
share.putExtra(Intent.EXTRA_TEXT, "My Image");
startActivity(Intent.createChooser(share, "Share Image"));
Works perfectly fine now.
What i have done to post image on facebook is instead of passing it directly i create a function and write it like this :
private void ShareWall(String message) {
Bundle parameters = new Bundle();
// share msg
parameters.putString("message", message);
// shre image which you have define above
parameters.putString("picture", postImage);
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("response: ", response);
if (response == null || response.equals("")) {
response.equals("");
showToast("No Response.");
} else {
showToast("Message has been posted to your walll!.");
}
finish();
} catch (Exception e) {
showToast("Message failed to posdt on wall.");
e.printStackTrace();
finish();
}
}
Hope this help you.
You can still share images (but not text) from your app to Facebook even if you are not using the Facebook SDK.
Just make sure that you use Uri.fromFile instead of Uri.parse and it will work:
DO NOT USE:
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathToFile));
USE:
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(pathToFile)));
Here is a solution without using external file write:
Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
In this case, my image comes from an ImageView myImageView.