[android] Android: How to open a specific folder via Intent and show its content in a file browser?

I thought this would be easy but as it turns out unfortunately it's not.

What I have:

I have a folder called "myFolder" on my external storage (not sd card because it's a Nexus 4, but that should not be the problem). The folder contains some *.csv files.

What I want:

I want to write a method which does the following: Show a variety of apps (file browsers) from which I can pick one (see picture). After I click on it, the selected file browser should start and show me the content of "myFolder". No more no less.

enter image description here

My question:

How exactly do I do that? I think I came quite close with the following code, but no matter what I do - and I'm certain that there must be something I didn't get right yet - it always opens only the main folder from the external storage.

public void openFolder()
{
File file = new File(Environment.getExternalStorageDirectory(),
    "myFolder");

Log.d("path", file.toString());

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivity(intent);
}

This question is related to android android-intent directory android-sdcard

The answer is


Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:

Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);

Alas, the Files app currently contains a bug that causes it to crash when you try this using the external storage provider. Folders from third party providers however can be displayed in this way.


Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setType("text/csv");

intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
      startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);

} catch (android.content.ActivityNotFoundException ex) {
  ex.printStackTrace();
}

then you just need to add the response

public void  onActivityResult(int requestCode, int resultCode, Intent data){

switch (requestCode) {
  case 0: {
     //what you want to do
    //file = new File(uri.getPath());
  }
}
}

Thread is old but I needed this kind of feature in my application and I found a way to do it so I decided to post it if it can help anyone in my situation.

As our device fleet is composed only by Samsung Galaxy Tab 2, I just had to find the file explorer's package name, give the right path and I succeed open my file explorer where I wanted to. I wish I could use Intent.CATEGORY_APP_FILES but it is only available in API 29.

  Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.sec.android.app.myfiles");
  Uri uri = Uri.parse(rootPath);
  if (intent != null) {
      intent.setData(uri);
      startActivity(intent);
  }

As I said, it was easy for me because our clients have the same device but it may help others to find a workaround for their own situation.


this code will work with OI File Manager :

        File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
        Uri uri = Uri.fromFile(root);

        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivityForResult(intent, 1);

you can get OI File manager here : http://www.openintents.org/en/filemanager


You seem close.

I would try to set the URI like this :

String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";

Intent intent = new Intent();  
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");   
startActivity(intent);

But it's not so different from what you have tried. Tell us if it changes anything ?

Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.


Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).


This should work:

Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");

if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
    startActivity(intent);
}
else
{
    // if you reach this place, it means there is no any file 
    // explorer app installed on your device
}

Please, be sure that you have any file explorer app installed on your device.

EDIT: added a shantanu's recommendation from the comment.

LIBRARIES: You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.


Here is my answer

private fun openFolder() {
    val location = "/storage/emulated/0/Download/";
    val intent = Intent(Intent.ACTION_VIEW)
    val myDir: Uri = FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", File(location))
    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        intent.setDataAndType(myDir,  DocumentsContract.Document.MIME_TYPE_DIR)
    else  intent.setDataAndType(myDir,  "*/*")

    if (intent.resolveActivityInfo(context.packageManager, 0) != null)
    {
        context.startActivity(intent)
    }
    else
    {
        // if you reach this place, it means there is no any file
        // explorer app installed on your device
        CustomToast.toastIt(context,context.getString(R.string.there_is_no_file_explorer_app_present_text))
    }
}

Here why I used FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

I tested on this device
Devices: Samsung SM-G950F (dreamltexx), Os API Level: 28


File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
                    .getLastPathSegment();
final String filePath = fullfileName.
                     substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);

fullfileName:

/mnt/sdcard/Download_Manager_Farsi/preview.png

filePath:

/mnt/sdcard/Download_Manager_Farsi


Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen enter image description here


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to directory

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit)

Examples related to android-sdcard

Android 6.0 Marshmallow. Cannot write to SD Card How to access /storage/emulated/0/ How to get file name from file path in android Android Open External Storage directory(sdcard) for storing file Android: How to open a specific folder via Intent and show its content in a file browser? Simple mediaplayer play mp3 from file path? error opening trace file: No such file or directory (2) How can I get the external SD card path for Android 4.0+? How do I adb pull ALL files of a folder present in SD Card Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?