Shreemaan Abhishek
Shreemaan Abhishek

Reputation: 1230

How to open a particular directory using Uri?

I want to open a particular directory (in a file explorer app) where images saved by my app are stored. I can get the Uri of that directory by Uri.parse(imagesDir.getAbsolutePath()). I tried this, this and others but it just does nothing. This is how my code looks as of now:

Uri selectedUri = Uri.parse(imagesDir.getAbsolutePath());
int OPEN_REQUEST = 1337;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(selectedUri, DocumentsContract.Document.MIME_TYPE_DIR);
if (intent.resolveActivityInfo(getPackageManager(), 0) != null) {
    startActivityForResult(intent, OPEN_REQUEST);
} else {
    Log.e("MainActivity", "Could not launch intent");
}

P.S: The value of imagesDir.getAbsolutePath() = /storage/emulated/0/Draw Easy

Upvotes: 0

Views: 429

Answers (2)

Michael Kazarian
Michael Kazarian

Reputation: 4462

SAF is pain. Uri.fromFile(file.getAbsolutePath()) doesn't work because returns uri likes file://sdcard.... But DocumentsContract.EXTRA_INITIAL_URI works with content. Below works for me:

private void selectDir() {
    Uri d = Uri.parse("content://com.android.externalstorage.documents/document/primary:Download");
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, d);
    startActivityForResult(intent, PICK_WDI_FILE);
}

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007534

I want to open a particular directory where images saved by my app are stored

Android has never really supported this.

I can get the Uri of that directory by Uri.parse(imagesDir.getAbsolutePath()).

That is an invalid Uri. At best, use Uri.fromFile(imagesDir).

This is how my code looks as of now

ACTION_OPEN_DOCUMENT does not take a Uri in the "data" facet.

The closest thing to what you want is to add EXTRA_INITIAL_URI to the Intent. However, this is only documented to work with a Uri that you previously obtained from ACTION_OPEN_DOCUMENT or ACTION_OPEN_DOCUMENT_TREE. It is unlikely to work with a Uri from some place else, such as from some File.

Upvotes: 1

Related Questions