Intent ACTION_GET_CONTENT returns uri even for deleted files
Asked Answered
H

2

6

I am trying to read pdf files in the android app.

Fire following intent to get URI.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, PDF_FILE_SELECTOR_INTENT_ID);

Problem is, the Downloads folder also shows old files that I have deleted. Also, when I select those files a valid URI is returned in onActivityResult(). When I create File from URI and check exists() it returns false which makes sense as I have already deleted the file from the Downloads folder.

How can I make sure that the Downloads folder shown on ACTION_GET_CONTENT shows only files which are currently present and not deleted ones?

Thanks.

Hood answered 12/3, 2019 at 13:24 Comment(3)
This is the intented behavior. URI(s) are not updated instantly, so, they may point to null, non-existant, or even different kind of targets (audio, images, etc.)Riker
Wouldn't you need a content provider to do this for you?Caduceus
in which device you are testing. And what is android os version?Shoshonean
G
2

Instead of

intent.setType("application/pdf"); use the Intent.EXTRA_MIME_TYPES in the putExtra

In Java:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {
                "application/pdf", // .pdf
        });
        startActivityForResult(intent, REQUEST_CODE);

In Kotlin

startActivityForResult(
        Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"
            putExtra(Intent.EXTRA_MIME_TYPES, arrayOf(
                    "application/pdf", // .pdf
            ))
        },
        REQUEST_CODE
      )

Update: Actual Download Folder & "Downloads" folder different in this case.

Download is for your actual downloaded files Downloads is a history folder behaves like a short-cut and it's not cleared automatically when the actual file pointed to is manually removed. This might be most likely an expect behavior.

In your case , you need to hide the downloads folder ( still you can use Download). using this line of code will show "Internal storage" by default:

intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
Geraldo answered 29/12, 2020 at 12:4 Comment(1)
For me, with the code, the old already deleted folders in Downloads is still shown. How to refresh?Stipulate
H
0

Call addCategory(Intent.CATEGORY_OPENABLE) to your Intent as recommended here: https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT

Habile answered 28/12, 2020 at 19:8 Comment(1)
with CATEGORY_OPENABLE still shows a lot of previously deleted files...Stipulate

© 2022 - 2024 — McMap. All rights reserved.