Getting pdf or doc file from Downloads Folder in Android

Viewed 645

I'm trying numerous ways to open the Downloads folder of the user and allowing the user to ONLY select a doc or pdf file to open up. Majority of the methods out there have been deprecated and their alternatives just don't seem to work for me.

Current Code:

// I've heavily altered the code but hope you guys understand the gist of it.


//Steps:
// Open the Downloads folder 
// Let user select the pdf or docx.
// Open the doc or pdf.

        // Adding Syllabus Function Method Here.
        addSyllabus = findViewById(R.id.add_syllabus_button);
        addSyllabus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview = (WebView) findViewById(R.id.webView);
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                webview.getSettings().setJavaScriptEnabled(true);
                String filename = "https://s25.q4cdn.com/967830246/files/doc_downloads/test.pdf";
                webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
                webview.setWebViewClient(new WebViewClient() {

                    public void onPageFinished(WebView view, String url) {
                        // do your stuff here
                        progressbar.setVisibility(View.GONE);
                    }
                });
            }

        });

Appreciate it, thanks.

1 Answers

An Intent from DocumentsProvider is probably your best bet.

From this Google Guide:

private void openFile(Uri pickerInitialUri) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/pdf");

    // Optionally, specify a URI for the file that should appear in the
    // system file picker when it loads.
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);

    startActivityForResult(intent, PICK_PDF_FILE);

You can use setType as shown and if you want to default to Downloads, you can use putExtra as shown. Change pickerInitialUri to the correct URI, which I think can be found as a constant: Environment.DIRECTORY_DOWNLOADS.

Update: I realize now you wanted more than one filetype. Per this thread: you can use:

String [] mimeTypes = {"application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);

(I got the MIME type strings from mozilla.)

Related