I've coded my own file explorer and now I want to start to Implement capabilities to open various files. I have implemented Mime Types and all other things but how can I parse specific selected file to specific "viewer activity"? I know by using intents but how to receive it in that viewer app and use it. Many thanks guys :)
Something like this should work. Change file to whatever you want.
File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");
int index = file.getName().lastIndexOf(".") + 1;
String extension = null;
if (index > 0) {
extension = file.getName().substring(index);
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri u = Uri.parse("file://" + file.getAbsolutePath());
String mimeType = null;
if (extension != null) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
if (mimeType == null) {
mimeType = "*/*";
}
intent.setDataAndType(u, mimeType);
try {
startActivity(Intent.createChooser(intent, "Open with..."));
} catch (ActivityNotFoundException e) {
// handle the exception
}
Related
i'm getting a pdf file from an api, and i got something like that http://x/docs/document1
In my android project, i have like this:
try{
Android.Content.Intent activity = new Android.Content.Intent(this, typeof(WebViewPDF));
activity.AddFlags(Android.Content.ActivityFlags.GrantReadUriPermission);
activity.AddFlags(Android.Content.ActivityFlags.NoHistory);
string uriAndroid = "http://x/docs/document1";
activity.PutExtra("url", JsonConvert.SerializeObject(uriAndroid));
StartActivity(activity);
}catch (Exception){
...
}
The main problem is, i cannot modify the api, so the endpoint is http://x/docs/document1, but if i try another uri, with the .pdf extension, for example https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf it works fine.
I don't know if i need to get that info from the API in a different way,
How can i show the pdf in the webView or external app without download first the doc?
The solution was download first and then open from local.
void PrintPdf(Uri uri)
{
var webClient = new WebClient();
webClient.Proxy = WebRequest.DefaultWebProxy;
webClient.Credentials = new NetworkCredential("UserName", "Pass");
webClient.Encoding = Encoding.UTF8;
var bytes = webClient.DownloadData(uri);
var text = bytes; // get the downloaded text
string localFilename = "NameforPdf.PDF";
string localPath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString(), localFilename);
File.WriteAllBytes(localPath, text); // writes to local storage
bool exists = File.Exists(localPath);
if (exists)
{
Java.IO.File file = new Java.IO.File(localPath);
file.SetReadable(true);
//That's the important part, notice the content://
Android.Net.Uri uriLocal = Android.Net.Uri.Parse("content://" + localPath);
Intent intent = new Intent(Intent.ActionView);
intent.SetFlags(ActivityFlags.NewTask);
intent.SetDataAndType(uriLocal, "application/pdf");
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
try
{
StartActivity(intent);
}
catch (Exception)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "pdf reader not installed", ToastLength.Short).Show();
}
}
}
I have used he Download Manager Class to download a text file from the server and stored it in the common external storage. Then I want to show the text file, may be using the listView class. I have searched the web and found that there are many examples showing how to display a text file from the App's resources. However, how can I show the file which is stored in a specific file path?
Thank you very much.
In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:
<TextView
android:id="#+id/text_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
And your code will look like this:
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
Also, put external storage read permission to manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
OR
You can also use default intent to do the JOB!
File txtfile = new File("/sdcard/some_file.txt");
Intent i = new Intent();
i.setDataAndType(Uri.fromFile(txtfile), "text/plain");
startActivity(i);
--
Try below code.
private void openFile() {
File file = new File("file_path");
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(path);
intent.setType("text/plain");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No application found",
Toast.LENGTH_SHORT).show();
}
}
You can open file from sd card by using code given below in external application which compatible to file extension,
public void openDocument(String fileName) {
File file = new File(Environment.getExternalStorageDirectory(), DATA_DIRECTORY + "/" + fileName);
Uri fileUri = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String extension = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (extension.equalsIgnoreCase("") || mimetype == null) {
// if there is no extension or there is no definite mimetype, still try to open the file
intent.setDataAndType(fileUri, "application/*");
} else {
intent.setDataAndType(fileUri, mimetype);
}
// custom message for the intent
startActivity(Intent.createChooser(intent, "Choose an Application:"));
}
Just want to confirm that is it possible that when i click on file of any extension will open up with its compatible software in android phone or display me the list of software’s present in mobile which can open the file and if it didn't found any software it will indicate user to first download the software to open that particular file (All this thing need to be done pro grammatically).
Thanks.
Any help will be appreciated.
In order to open the file you can use the following method, If there is no application that can handle given file, it simply shows a Toast saying no application found.
private void viewFile(String filePath, String title, int fileType) {
Uri uri = Uri.parse("file://" + filePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
String dataAndType = getIntentDataAndType(filePath);
intent.setDataAndType(uri, dataAndType);
intent.putExtra(Intent.EXTRA_TITLE, title);
// Verify that the intent will resolve to an activity
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(getActivity(), "No Application found", Toast.LENGTH_SHORT).show();
}
}
UPDATED :
For finding the mime type of the file.
private String getIntentDataAndType(String filePath) {
String exten = "";
int i = filePath.lastIndexOf('.');
// If the index position is greater than zero then get the substring.
if (i > 0) {
exten = filePath.substring(i + 1);
}
String mimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(exten);
mimeType = (mimeType == null) ? "*/*" : mimeType;
return mimeType;
}
I wish I could open any file type using mobile applications.
Here is the code :
File mFile = new File( file.getLocalPath() + file.getFileName() );
Log.i("path", file.getLocalPath() + file.getFileName());
if( mFile.exists() )
{
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(mFile.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Log.i("type", type);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri data = Uri.fromFile(mFile);
Log.i("uri", data.toString());
intent.setDataAndType( data, type );
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
}
}
Logs :
Path : /data/data/com.package.name/files/sbx/523/filename.jpg
Type : image/jpeg
Uri : file:///data/data/com.package.name/files/sbx/523/filename.jpg
All logs are displayed therefore the file exists.
However, during the opening of the gallery, I get an "Unable to find item".
Where is the problem ? Are there other solutions ?
The problem is that you are trying to open file which is in android private area thats why during the opening of the gallery, you get an "Unable to find item". You have to put your file in local. If you want to open a file of android private area you should be rooted.
I am Working email attachment .I am facing one problem while attachment .Problem Is that i want to sent a mail with attachment .I have one file on this path sdcard0 then fgg then hh.html.When I debug
on this File file = new File(attachments.getString(i));
it show file:/storage/sdcard0/fgg/hh.html
But After this it not go to if condition why ?
File file = new File(attachments.getString(i));
if (file.exists()) {
Uri uri = Uri.fromFile(file);
uris.add(uri);
}
Here is my hole code
JSONArray attachments = parameters.getJSONArray("attachments");
if (attachments != null && attachments.length() > 0) {
ArrayList<Uri> uris = new ArrayList<Uri>();
//convert from paths to Android friendly Parcelable Uri's
for (int i=0; i<attachments.length(); i++) {
try {
File file = new File(attachments.getString(i));
if (file.exists()) {
Uri uri = Uri.fromFile(file);
uris.add(uri);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error adding an attachment: " + e.toString());
}
}
if (uris.size() > 0) {
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling attachments param: " + e.toString());
}
Uri to file will need triple slashes :
file:///storage/sdcard0/fgg/hh.html
As you can see here.
But i twill probably not work, so try to remove the "file:" part of your string :
File file = new File(attachments.getString(i).replace("file:","");
in a URI, you have different parts.
First the scheme:
http://
file://
ftp://
Then the path you want to access:
myfile.txt
videos/myvideo.avi
/storage/sdcard0/fgg/hh.html
So your complete URI should be:
file:///storage/sdcard0/fgg/hh.html
More information here:
http://developer.android.com/reference/java/net/URI.html
You can then build your File and check if it exist with this snippet
Uri.Builder builder = new Uri.Builder();
builder.scheme("file");
builder.path(myFilePath);
Uri uri = builder.build();
File file = new File(uri.getPath());
if (file.exists()) {
uris.add(uri);
// do whatever you want
}
EDIT:
If your JSON send you complete URI path, use this code instead:
Uri uri = Uri.parse(attachments.getString(i));
File file = new File(uri.getPath());
if (file.exists()) {
uris.add(uri);
// do whatever you want
}
Try two forward slashes after :
file://storage/sdcard0/fgg/hh.html
edit:
should be 3 forward slashes