How to open an excel file in android - android

I have downloaded the excel file to sdcard. want to open the file in my app and process it.
Is there any way or any intent to open an excel file in android. I

Use the below mentioned code and try:
File file = new File(Environment.getExternalStorageDirectory()+ "/filepath/" + filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-excel");
startActivity(intent);

Use this piece of code which can be used to open arbitrary file (not only Excel).
General idea is to get based on file mime type which Intent can handle it and then start those Intent. For sure it may happen that system doesn't have any intents to handle it or may have several Intents. Anyway here's general direction:
Get mime type for given filename
public String getMimeType(String filename)
{
String extension = FileUtils.getExtension(filename);
// Let's check the official map first. Webkit has a nice extension-to-MIME map.
// Be sure to remove the first character from the extension, which is the "." character.
if (extension.length() > 0)
{
String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
if (webkitMimeType != null)
return webkitMimeType;
}
return "*/*";
}
Then get default intent which will handle given mime type
public Intent getDefaultViewIntent(Uri uri)
{
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
// Let's probe the intent exactly in the same way as the VIEW action
String name=(new File(uri.getPath())).getName();
intent.setDataAndType(uri, this.getMimeType(name));
final List<ResolveInfo> lri = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(lri.size() > 0)
return intent;
return null;
}
And as final step just start Intent returned by getDefaultViewIntent()

Try this:
public void ouvrir(View view) {
String csvFile = "myData.xls";
File yourDir = new File(Environment.getExternalStorageDirectory()+ "/CHETEHOUNA/" + csvFile);
String davUrl = "ms-excel:ofv|u|" + yourDir.toString();
Uri uri = Uri.parse(davUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}

Uri path = Uri.fromFile(file);
Intent excelIntent = new Intent(Intent.ACTION_VIEW);
excelIntent.setDataAndType(path , "application/vnd.ms-excel");
excelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(excelIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,"No Application available to viewExcel", Toast.LENGTH_SHORT).show();
}

Can you elaborate?
If you want to read excel file from SD card using File, here is the code
File root = Environment.getExternalStorageDirectory();
File excelFile = new File(root, "filename.xlsx");

Related

Android - How do I open a file in another app via Intent?

I'm trying to open a file using another app, i.e. opening a .jpg with Gallery, .pdf with Acrobat, etc.
The problem I'm having with this is when I try to open the file in the app, it only opens the chosen app instead of opening the file within the app. I tried following Android open pdf file via Intent but I must be missing something.
public String get_mime_type(String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = null;
if (ext != null) {
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
return mime;
}
public void open_file(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), filename);
// Get URI and MIME type of file
Uri uri = Uri.fromFile(file).normalizeScheme();
String mime = get_mime_type(uri.toString());
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(mime);
context.startActivity(Intent.createChooser(intent, "Open file with"));
}
As far as I can tell, it returns the right URI and MIME type:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg
Posting my changes here in case it can help someone else. I ended up changing the download location to an internal folder and adding a content provider.
public void open_file(String filename) {
File path = new File(getFilesDir(), "dl");
File file = new File(path, filename);
// Get URI and MIME type of file
Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
String mime = getContentResolver().getType(uri);
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mime);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
I used this piece of code and it worked perfectly fine on android 6 and below not tested on the higher version
public void openFile(final String fileName){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
.getAbsolutePath()+ File.separator+"/Folder/"+fileName));
intent.setDataAndType(uri, "audio/mpeg");
startActivity(intent);
}

How to read/open PPT files in Android?

[This question may be duplicate, but i din't find what i am looking for]
[Read]How can we open files like ppt, doc, pps, rtf, etc. in Android?
I am having PPT files. In my app, i have a list view which display the PPT file list available in my private app folder. In click of particular file, i want to open corresponding PPT file for reading in my App.
The App which i am creating is just like collection of PPTs and reading them one by one.
Please provide any API/Example/Links.
You need to use other application to open your ppt files , Make sure that file location you are providing is accessible to other application. Try with following :
final Uri uri = Uri.fromFile(file);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if(list.size() > 0)
startActivity(context, intent);
Available application will be shown to user and user can choose application which can open.
private void openPPT(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-powerpoint");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

Open any type of file of Android without declaring MIME type explicitly

I am using this method to open launch an Intent to open a file on Android (I've described my problems in the comments):
public static void openFile(Context context, String fileName) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setType(FileHelper.getMimeType(file)); // this doesn't work for PDF files
// opens Intent but then the chosen application doesn't open the file
intent.setType("application/pdf"); // this works correctly for PDF files
intent.setData(Uri.parse("file://" + getPath(context) + fileName));
context.startActivity(intent);
}
I would like to have a single method that would open any kind of file, without having to explicitly specify the MIME type, is that possible?
Mime type is needed to open the file i.e. we have to set Data and Type. You can use this function to open any file:
public void openFile(Context ctx,String filepath)
{
Uri ttt = Uri.parse("file://" + filepath);
Intent intent = new Intent(Intent.ACTION_VIEW);
String arr[] = filepath.split("\\.");
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(arr[arr.length - 1]);
intent.setDataAndType(ttt, mimeType);
ctx.startActivity(intent);
}
However, there will be problem in files without extension.

Need to know about app chooser in android

I have a list of files in listview .. these files actually reside on sd card. Now i want to open these files by using an app picker. I.e if this file is an image it should show all applications in my phone that can open jpg type files in application chooser box.
How can i do this .. can someone give me any idea about it?
Any help is appreciated :)
Thanks in advance
I found dis piece of code ..how can i use it in my application?
public class Redirector {
public static void showActivityWithChooser( Context context, int chooserLabelTitleId, Intent intent ) {
try {
context.startActivity( Intent.createChooser( intent,
context.getResources().getString( chooserLabelTitleId )) );
} catch( Exception e ) {
e.printStackTrace();
}
}
public static void viewInExternalApplication( Context context, String url ) {
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setData( Uri.parse( url ) );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET );
showActivityWithChooser( context, R.string.open_chooser_title, intent );
}
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/YOUR_PATH_TO_Images/";
try {
if (f.exists()) {
File file = new File(path
+ listViewArray.get(position).getImageName());
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),
"image/*");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(target,
"Open With");
startActivity(intent1);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No Pdf found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Just send the intent. Android will show an app chosser itself, if more than one app capable of showing the specified file type is installed, or start the app directly, if there's just one (or the user selected "always"/"remember my choice" in the app chooser)
To get the applications that can successfully open a given intent you'll use the PackageManager. Simply construct the intent as above and then use this code to get the applications that can handle the intent.
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory("android.intent.category.LAUNCHER");
myIntent.setType("mp3");
PackageManager manager = getPackageManager();
List<ResolveInfo> info = manager.queryIntentActivities(myIntent,PackageManager.MATCH_DEFAULT_ONLY);
This will give you all the information on the programs that can handle the intent, including icon, and packagename. You can then create a dialog box with these options and save the option the user chooses.
1.This is question is related to Mime type
First get extenstion of file and set type of mime used by element into list
private String extenstionFile(String url) {
if (url.indexOf("?")>-1) {
url = url.substring(0,url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") );
if (ext.indexOf("%")>-1) {
ext = ext.substring(0,ext.indexOf("%"));
}
if (ext.indexOf("/")>-1) {
ext = ext.substring(0,ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
Than open supported type of application list:-
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
//Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(extenstionFile(getFile().toString()).substring(1));
newIntent.setDataAndType(Uri.fromFile(getFile()),mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
_context.startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(_context, "No handler for this type of file.", 4000).show();
}
After selecting the file please check whic file is it (ex pdf , jpg) , After that create an ACTION_VIEW intent and set the type of intent according to selected file type. Now brocast the intent , System itself will show you the list of applications thats supports the viewing of yor file.
Check below link you will get better idea.
http://developer.android.com/guide/components/intents-filters.html

How to use Intent.ATTACH_DATA

I'm trying to implement "set as" functionality for images. I'm using Intent.ATTACH_DATA so users can at least choose contact photo and wallpaper. The extras I should pass confuse me. If I read the documentation right,
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setType("image/*");
intent.setData(mImageCaptureUri);
startActivity(Intent.createChooser(intent, "hey"));
Should be all. This works for wallpapers, but with megapixel data, the app crashes, because no crop activity could be found. Does someone have a working example? The official gallery app does manage to find the camera.crop activity...
A general hint on where to find elaborate system intent documentation is welcome as well.
After a long and winding road through the android source, I found the actual code in the default gallery (gallery3d) app. I adapted for use in my own application, and rewrote it again for convenience when importing in other applications. If you use or appreciate this, I ask that you upvote this answer.
Adapted from : gallery3d source at grepcode
Usage: change first line to match the full path (starting with /mnt/) of your photo.
add string "set_as" to your strings.xml as the action chooser title.
String absolutepath = MyApplication.appRootDir + relpath;//change for your application
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = absolutepath.substring(absolutepath.lastIndexOf('.') + 1);
String mimeType = map.getMimeTypeFromExtension(ext);
Uri uri = Uri.fromFile(new File(absolutepath));
intent.setDataAndType(uri, mimeType);
intent.putExtra("mimeType", mimeType);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Activity activity = (Activity) this;
activity.startActivity(Intent.createChooser(
intent, activity.getString(R.string.set_as)));
Above answers are great , however here is one i tested and used.
private void setAsWallpaper(String path_of_file) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_ATTACH_DATA);
File file = new File(path_of_file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setDataAndType(FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file), getMimeType(path_of_file);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Exception generated", Toast.LENGTH_SHORT).show();
}
}
private static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
and simply call setAsWallpaper(path);
here path is absolute path of file .

Categories

Resources