I have this code:
File file = new File("android.resource://" + getPackageName() + "/" + R.raw.intro_sad);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
it results from an error in file path. how to get the filepath?
I don't think raw resources are accessible by external applications (which is what I think you're trying to do). Instead you should copy the file to an external storage or a WORLD_READABLE folder and then use the path of the copy.
Related
Where a downloaded file is stored and where Uri goes to pick it up are not the same.
Java.IO.File file = new Java.IO.File(Query.filePathh);
Console.WriteLine("Downloaded file PATH: " + Query.filePathh);
Intent open = new Intent(Intent.ActionView);
open.AddFlags(ActivityFlags.GrantReadUriPermission);
open.SetFlags(ActivityFlags.NewTask);
Context context = Android.App.Application.Context;
Android.Net.Uri fileUri = FileProvider.GetUriForFile(context, "com.companyname.Login.provider", file).NormalizeScheme();
Console.WriteLine("File uri: " + fileUri.Path);
open.SetDataAndType(fileUri, "*/*");
Intent intentC = Intent.CreateChooser(open, "Open With");
intentC.AddFlags(ActivityFlags.GrantReadUriPermission);
intentC.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intentC);
We get pop-up that asked how to open a file, but when the application tries to open it, it crashes with an error that the file path does not exist.
While debugging we tried to see file locations on where the file is downloaded and what Uri is calling and we get:
For storage_path:
storage/emulated/0/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
For Uri path:
/external/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
We can open the file normally if we go to Download folder in our Emulator.
Any suggestions on what to do?
I am creating an app where every time press the download button it's create a pdf file in my storage.My problem is newly created file overwrites the existing file with same file name.I need to download with new filename.What i am trying
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
This above lines of program create files but i need to open the last download file
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
These above lines of code generate an error.
Error:File no longer exist,the file maybe deleted or changed or
removed by another program
1.create a new file and prevent overwiting whenever i click the button
2.open the last downloaded file
I am new to Android and little confused about that and kindly need some help from you guys.
You call Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf")); for open file, so why you added /NewPDF.pdf because its already in your file. just remove it.
Replace this line
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
to
Uri uri = Uri.fromFile(new File( file));
You are assigning the same name to every file you create. Try giving a unique name like this:
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
the randomUUIDString will be your unique string for the pdf files. Also, store these strings in a SQLite db if you wish to use them.
The path you have entered in intent not matching with the created file path.
Try this.
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
String lastFilePath = null;
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
lastFilePath = file.getAbsolutePath();
Then you can open the file like this.
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(lastFilePath));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Hope it helps:)
Replace if with while and display Intent:
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
int increase = 0;
file = new File(dirpath+"/NewPDF.pdf");
while(file.exists()) {
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");
}
file.createNewFile();
... store data in file here ...
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Use Time stamp instead of Counter, so that you can create a new file every time.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
Date timeStamp = new Date();
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +formatter.format(timeStamp )+".pdf");}
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 have a function that downloads and extracts a zip file.
Its extracted to the external storage in: ../Android/data/packagename/..
When I try the following intent to view a .mp4 video for example, its opened in a video player and says that it can't open the file. (not only .mp4 files)
Uri uri = Uri.parse(Helper.getStorageDir(getActivity()) + "/" + mediaObject.getLinkOffline());
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(mediaObject.getLinkOffline().substring(mediaObject.getLinkOffline().lastIndexOf(".") + 1, mediaObject.getLinkOffline().length()));
newIntent.setDataAndType(uri, mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No handler for this type of file.", 4000).show();
}
However, when I go through a file explorer and open the same file there is no problem.
I have there read/write permissions in my manifest. But thats obviously not the problem since I can read write the file and can also check the the file exists. It just wont let an external app open the file through an intent from my app.
Am I missing something?
EDIT: when I debug and check the mime type for the mp4 file it is "video/mp4".
How can I create internal folder in my application to put the image captured in it
after that get the image folder path ???
inside Android you can create folder either on SD card (External Storage) or on internal memory.
the following command create a folder
file.mkdir()
so when you provide a file path like bellow
File file=new File(PATH/FOLDER_NAME);
it will create on specific location but if you do not provide path it will simply create folder on internal memory. which is basically
data/data/YOUR_APPLICATION_PACKAGE/
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
File file = new File(path, "/" + fname);
You can add whatever folder name you want after "DIRECTORY_MOVIES" or "DIRECTORY_PICTURES" or whatever
Simply you can add this code on your camera capture button
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Your Folder Name");
imagesFolder.mkdirs();
Calendar cal = Calendar.getInstance();
File photo = new File(Environment.getExternalStorageDirectory()
+ "/Your Folder Name", (cal.getTimeInMillis() + ".jpg"));
mCapturedImagePath = photo.getAbsolutePath();
Uri uriSavedImage = Uri.fromFile(photo);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, PICK_FROM_CAMERA);
The above code create a folder and save an Image into your SD card
path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_MOVIES);
File file = new File(path, "/" + fname);
You can add whatever folder name you want after "DIRECTORY_MOVIES" or "DIRECTORY_PICTURES" or whatever - and it's internal to the device, and not external like on an SD card. It simply means that other apps can see this data and that it's not internal to the app and invisible to other apps or users