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;
Related
I don't want to send emails to other users. I only want to open the launching activity of Email. I have tried it through different ways but every time send email(compose) is opening. But i want to open Email app only nothing else(Sent, outbox, spam, Trash etc).
My code is below
Intent intent = new Intent(Intent.ACTION_SENDTO)
.setData(Uri.parse("mailto:"));
//check if the target app is available or not
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Again, This code opens the send email to(compose) option. But i want to open Email app only nothing else(Sent, outbox, spam, Trash etc).
Use this code to open default Mail Application :
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(Dashboard.this, "There is no email client installed.", 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 trying to save my images to a folder into my Samsung galaxy s6 edge. I'm a beginner and have created an application to practice take an intent image and return the image to my application where I then choose an image filter and further want to save it to my device. I cant understand why it doesn't work. The error I get is:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Pictures.jpg: open failed: EACCES (Permission denied)
And here is the code:
public void savePhoto(View view) {
if(currentBitmap != null) {
File storageLoc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(storageLoc, "Pictures.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
currentBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Context context = getApplicationContext();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(file));
context.sendBroadcast(scanIntent);
Toast.makeText(getApplicationContext(), "Your image has been saved!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "No image taken!", Toast.LENGTH_SHORT).show();
}
}
Im using API15 if it have something with that to do. The rest of my code works good without saving images. If someone can see the problem I would be grateful.
Your android version seems to be above Marshmallow. Means you need to check permission at runtime. As log shows Permission denied.
You can do it in two ways
Checking permission by ContextCompat.checkSelfPermission() way
By declaring ANDROID_BUILD_TARGET_SDK_VERSION=22 in gradle
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();
}
After using this code:
public void getContent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_CODE_GET_CONTENT);
} catch (ActivityNotFoundException e) {
// No compatible file manager was found.
Toast.makeText(this, R.string.no_filemanager_installed,
Toast.LENGTH_SHORT).show();
}
}
the phone pops up a window where you can choose between audio or images file. I just want the audio and I don't want that the user can choose the image files. how can I do to not show this window and automatically go to audio selection?
Try intent.setType("audio/*");