Rostislav Shtanko
Rostislav Shtanko

Reputation: 11

Android:How to open pdf?

I try to open pdf, but when I press the button, nothing happens. Where is my mistake?

OnClickListener oclBt2 = new OnClickListener(){
            public void onClick(View v) {
                File file = new File("http://testserv1.p.ht/1/ksu016.pdf");

                if (file.exists()) {
                Uri path = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);   
                try {
                    startActivity(intent);
                    } 
                catch (ActivityNotFoundException e) {
                     e.printStackTrace();
                    }
                }
            }
        };

I corrected my code, but it doesn't work again :( when I press the button, appears the window(Sorry, but my reputation doesn't allow to post images)

OnClickListener oclBt2 = new OnClickListener(){
            public void onClick(View v) {
                Uri path = Uri.parse("http://testserv1.p.ht/1/ksu016.pdf");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                startActivity(intent);
                } 
                catch (ActivityNotFoundException e) {               
                mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url=http://hostforandroid.elitno.net/pdf-test.pdf" );
                setContentView(mWebView);
                }               
            }
        };

Upvotes: 1

Views: 130

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006539

First, File is for local files, not http URLs. Use Uri.parse("http://testserv1.p.ht/1/ksu016.pdf"); to get a Uri pointing to an http URL.

Second, there may be no PDF viewers that are set up to directly download from an HTTP URL. For greater compatibility, you can arrange to download the PDF first (using DownloadManager or your own HTTP client code), then view the local PDF file.

Upvotes: 1

Related Questions