user1508544
user1508544

Reputation: 3

How can I open a PDF file via my Android app?

I want to open a pdf file via an Android app. So far I have written the following code:

public class PdfopenActivity extends Activity {
    String selectedFilePath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnOpen=(Button)findViewById(R.id.button1);

        btnOpen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Sample.pdf is my file name it is in /Root/Download/Sample.pdf 
                // path of the file

                File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sample.pdf");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),"application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });
    }
}

The pdf is 175kb and I can open the file directly on my Galaxy Tab2 tablet, but when I run my my program to open it I get the error:

An Error Occurred while opening the document.

Can anyone tell me where I am going wrong?
.

Upvotes: 0

Views: 2828

Answers (1)

AkashG
AkashG

Reputation: 7888

Try this out:

        Button btnOpen=(Button)findViewById(R.id.button1);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File("/sdcard/sample.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);

                    try {
                        startActivity(intent);
                    } 
                    catch (ActivityNotFoundException e) {

                    }
                }
            }
        });

Hope this will help you.

Upvotes: 3

Related Questions