Launching an intent for file : "Unable to find item" - android

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.

Related

Display PDF from uri in Android

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();
}
}
}

Read file of any extension in android programmatically

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;
}

Open files from own file explorer

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
}

Open file and folder in other app

I got a activity that holds a path to a file (with unknown mime type).
I got 2 buttons. The one should open the folder in a file manager choosen by user.
The other should open the file in a application that fits to the filetype.
Clicking buttons work. openFolder let me choose a filemanager: using androzip or root explorer takes me to sdcard but astro wants me to choose a file as if i upload a file to a oneclickhoster. OpenFile gives me no choise but opens a hex Editor which unfortunatli says the file is "null".
public void openFolder(View v)
{
File f=new File(path);
if(f.exists())
{
String folder=f.getAbsolutePath().replace("/"+f.getName(),"")+"/";
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(folder);
intent.setDataAndType(uri, "file/*");
startActivity(Intent.createChooser(intent, "Open folder"));
}
}
public void openFile(View v)
{
File f=new File(path);
if(f.exists())
{
//example for path: path=/storage/sdcard0/test.mp3
Intent intent = new Intent(Intent.ACTION_EDIT);
Uri uri = Uri.parse("file:/"+path);
intent.setDataAndType(uri, getMIME());
startActivity(Intent.createChooser(intent, "Open file"));
}
}
private String getMIME()
{
String type =null;
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
if(type.equals("") || type == null)
return "UNKNOWN";
else
return type;
}
EDIT: the problem for opening the file was Intent.ACTION_EDIT, it should be Intent.ACTION_VIEW.
But I still don't know how to open the folder.

Why file exists statement not true in android?

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

Categories

Resources