Alex
Alex

Reputation: 1644

Android select PDF using Intent on API 18

I'm using following codes to select a PDF file using Intent. It perfectly works on Android 5.0+ but no suitable application to open a PDF file message appears on API 18.

public static Intent pickPdf() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    return intent;
}

startActivityForResult(Intent.createChooser(pickPdf(), "Open with"), PICK_PDF);

Upvotes: 6

Views: 3159

Answers (2)

Zahid Iqbal
Zahid Iqbal

Reputation: 484

You can try this code to select pdf from storage and get URI

private static final int PICK_PDF = 123;

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("application/pdf"); startActivityForResult(intent, PICK_PDF);

put below code in onActivityResult

if (requestCode == PICK_PDF && resultCode == Activity.RESULT_OK) {
        if (data == null) {
            //Display an error
            Toast.makeText(this, "something went wrong Retry", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            InputStream inputStream = getContentResolver().openInputStream(data.getData());
            Uri uri = data.getData();
            //here is the uri you can do what you want
            Log.e(TAG, "onActivityResult: " + uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error:"+e.toString(), Toast.LENGTH_SHORT).show();
        }
     }

Upvotes: 0

Sipty
Sipty

Reputation: 1154

As @CommonsWare suggested -- there is no guarantee that an app, which handles PDFs is installed.

How I've solved this before is by using an App Chooser, like so:

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

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
    ShowToast(TAG, "Unable to open PDF. Please, install a PDF reader app.");
}   

Upvotes: 2

Related Questions