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 ?
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'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 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);
}
I try to create directory on Tablet and want to see it.
I create directory with this code
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
I see everytime Directory created, But when I search Folder in file system, I can not see it. How can I make it visible. Am I making wrong?
EDIT:
I gave all permission on manifest. And I tried this code too
File direct = new File(Environment.getExternalStorageDirectory()+"/"+sDirectoryName);
if(!direct.exists())
{
if(direct.mkdir())
{
System.out.println("Directory created");
Toast.makeText(MainActivity.this, "Directory created", Toast.LENGTH_LONG).show();
}
else
{
System.out.println("Directory not created");
Toast.makeText(MainActivity.this, "Directory not created", Toast.LENGTH_LONG).show();
}
}
But this is not working for me too.
EDIT:
For refreshing I use this code.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
working.
Note: because Android uses the MTP protocol for USB connections sometimes a file or folder just wont show because everything is cached and may need a refresh.
More info: Nexus 4 not showing files via MTP
File does not create a file if it doesn't exist. It just stores the path to it. Your if statement shows it doesn't exist.
Try this...
public void createDirectory(String sDirectoryName)
{
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), sDirectoryName);
if (!file.exists()) {
file.mkdirs();
}
}
Use below code to create directory.
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
direct.mkdirs();
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Make sure that your manifeist have the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And in code
File directory = new File(Environment.getExternalStorageDirectory()+DOC_FOLDER_NAME);
// create directory if not exists
if(!directory.exists())
{
if(directory.mkdirs()) //directory is created;
Log.i(" download ","App dir created");
else
Log.w(" download ","Unable to create app dir!");
}
To create a dir:
if(!direct.exist()) {
if (direct.mkdir())
Log.i(TAG, "Directory created");
else
Log.w(TAG, "Failed to create directory");
}
and don't forget permissions in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Your print statement is confusing :
if(!direct.exist()) { // If directory does not exist
System.out.println("Directory created"); // Directory created not true
}
As just creating a File object it will not create directory the code should be:
if(!direct.exist()) { // If directory does not exist
direct.mkdir(); // Create directory
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
Also make sure to add android.permission.WRITE_EXTERNAL_STORAGE permission in your application.
Additionally its suggested not to use System.out.println in Android as On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.
in manifest add this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and this for java file:
File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
to delete it:
myDirectory.delete();
and this for File object for the parent directory:
//create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Is the issue not on the line
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
According to the documentation context.MODE_PRIVATE will only be visible within the app itself another program or user ID won't be able to find it.
try:
File direct = getDir(sDirectoryName, Context.MODE_WORLD_READABLE);
or
File direct = getDir(sDirectoryName, Context.MODE_WORLD_WRITEABLE);
http://developer.android.com/reference/android/content/Context.html