I am trying to edit an MSWord document from my app.
I decided to use an Intent to do this but MSWord can't seem to locate the document to edit. I'm not sure if I'm not correctly defining the location of the document, or if I'm not passing the uri correctly.
Intent intent = new Intent(Intent.ACTION_EDIT);
file = Environment.getExternalStorageDirectory().getPath()+"/mydoc.doc";
Uri uri = Uri.parse(file);
intent.setDataAndType(uri, "application/msword");
activity.startActivityForResult(intent, MSWORD);
The result I get is that MSWord launches and I get an error message:
"Can't open file"
"Try saving the file on the device and then opening it."
Documentation on MSWord and Intents seems to be very sparse!
At long last have found it - here for other frustrated developers!
File file = new File(Environment.getExternalStorageDirectory(),"Documents/101131new.docx");
Uri path = Uri.fromFile(file);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
objIntent.setDataAndType(path,"application/msword");
activity.startActivity(objIntent);
This allows you to work on the local file in the /Documents directory.
Please try below:
/**
* #param fileRelativePath should be relative to SDCard
*/
private void launchMSWorldToOpenDoc(String fileRelativePath) {
File file = new File(Environment.getExternalStorageDirectory(), fileRelativePath);
Uri path = Uri.fromFile(file);
Intent msIntent = new Intent(Intent.ACTION_EDIT);
msIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
msIntent .setDataAndType(path,"application/msword");
activity.startActivity(msIntent);
}
Related
I am developing an application, a function that I need is that I can open the camera to take a photo and store it in the path Pictures/Example I save the image in that path so that it can be opened from the google photos application.
With this fragment I create the path and name of the image and open the camera:
private void openCameraTocaptureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.cameraimage.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
My doubt is present when invoking createImageFile()
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES+"/Example");//********* Here is my doubt ******
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
So far the application meets what I need, takes a picture and stores it in Pictures/Example and can be viewed from the Photos application, but reading the documentation I found this:
getExternalStorageDirectory
This method was deprecated in API level 29.
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
I decided to use getExternalFilesDir, So I tried to replace
File storageDir = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES+"/Example");
with
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES+"/Example");
So the code looks like this:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES+"/Example");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
But this causes my photo to be stored in Android/data/com.example.cameraimage/files/Pictures/Example it is not the path I want and it is not shown in Photos App
The main question is, should I stop using getExternalStorageDirectory() even though it works?
If I have to change how can I use any of the alternatives so that I can store photos in Pictures/Example and display the images in the Photos application?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
//activity A intent
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent,Constant.ACTION.LOAD_GALLERY_ACTION);
//this is onActicityResult function
case Constant.ACTION.LOAD_GALLERY_ACTION:
Uri uri = data.getData();
if(mImage.size()<maxAddPic) {
mImage.add(copyGalleryPic(uri));
adapter.notifyDataSetChanged();
}
break;
//to copy the gallery photo,return the new file uri.
private Uri copyGalleryPic(Uri uri) {
String filePath = Environment.getExternalStorageDirectory() + "/images/"+"diary"+System.currentTimeMillis()+".jpg";
File outputFile = new File(filePath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
Bitmap bitmap;
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
} catch (IOException e) {
// ... handle IO exception
}
Uri newUri = FileProvider.getUriForFile(CreateDiaryActivity.this,"com.example.diary.cr",outputFile);
return newUri;
}
but there are some errors
the intent returns uri
"content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F29/ORIGINAL/NONE/41130179"
but debug info shows the code
"bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),
uri);" error : java.io.FileNotFoundException: open failed: ENOENT
(No such file or directory)
please help me ! Love you guys!
My English is not well. please use Simple words. Thank you!
which android version and which sdk-version are you using? I have an android-2.2 app that cannot receive intent permissions under android 7 see: https://github.com/k3b/intent-intercept/issues/4. I assume that recompiling with a more recent android-sdk might help.
Does you program work if you use an InputStream to read the picked image via getContentResolver().openInputStream(data.getData(uri)).
Since android-4.4 ACTION_PICK was replaced by ACTION_OPEN_DOCUMENT. My recent apps that use ACTION_OPEN_DOCUMENT together with openInputStream work as expected
I want to open a folder base on the path by device file manager .
I create a folder and save in save it into SharedPreferences .
now I want to open this folder .
I create a folder like this :
public static File myDirectory;
myDirectory = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_name));
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
in my application class.
and now I want to open this address:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ File.separator + getString(R.string.app_name) + File.separator);
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
how can I open it by default file manager ?
I'm trying to let a user export an excel file in my app and have the app automatically open the created excel file. The excel file is created and stored successfully using jxl, but when I try to open it with the Hancom Office Editor nothing happens other than my screen getting a dark overlay. Here's a gif:
I can't figure out what would cause this and can't find anything about it online.
I'm using the accepted answer from here to support my target SDK 28.
my export method:
public void onExport(View view){
try {
//write changes to excel file(changes made outide of function)
workbook.write();
workbook.close();
Toast.makeText(getApplication(),
"Data Exported to Excel Sheet", Toast.LENGTH_SHORT).show();
findViewById(R.id.btn_export).setEnabled(false);
//set file to saved excel file
File file = new File(Environment.getExternalStorageDirectory(),
race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
Log.i("path: ", path.toString());
intent.setDataAndType(path, "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
catch (ActivityNotFoundException e) {
Log.i("oh no:", "No application available to view excel");
}
}
My provider tag in AndroidManifest.xml(set as a child of ):
<provider
android:name=".GenericFileProvider"
android:authorities="com.something.racecalculator.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
I'm not getting any Errors or warnings as far as I can tell. Thanks for any help.
I'm not sure exactly what caused the problem, however, I suspect that I might have had the file path wrong. I changed a couple things (including where the excel files were being saved to. Changed from /storage/emulated/0/ to /storage/emulated/0/Samsung) and here is what worked:
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File("/storage/emulated/0/Samsung"+File.separator + race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(path, "application/vnd.ms-excel");
startActivity(intent);
remember that you need to implement a FileProvider if your target SDK is 24 or above
I want to open the HashTag-Page with the native facebook app.
This code works fine when opening profiles:
String facebookScheme = "fb://profile/" + facebookId;
Intent facebookIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(facebookScheme));
startActivity(facebookIntent);
But how to open HashTags like this?
https://www.facebook.com/hashtag/audi