Open In App

How to Implement PDF Picker in Android?

Last Updated : 28 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how we can implement a PDF picker in android studio and get the Uri and Path of the pdf. In this application, we will take permission from the user to Read External Storage and then show the Uri and path of the selected PDF to the user showing that we have successfully picked the PDF. Here is a sample video of what we are going to build in this application. Note that we are going to implement this application using Java language.

Step by Step Implementation

Step 1: Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? 

Step 2: Adding storage permission

Follow the path app > manifests > AndroidManifest.xml and paste the following piece of code in it.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Step 3: Working on XML files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp"
    tools:context=".MainActivity">
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_select"
        android:text="Select PDF"/>
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_uri"
        android:textSize="18sp"
        android:textAlignment="center"
        android:layout_marginTop="16dp"/>
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_path"
        android:textSize="18sp"
        android:textAlignment="center"
        android:layout_marginTop="32dp"/>
  
</LinearLayout>


Step 4: Working on java files

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail

Java




package com.example.pdfpicker;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variable
    Button btSelect;
    TextView tvUri, tvPath;
    ActivityResultLauncher<Intent> resultLauncher;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // assign variable
        btSelect = findViewById(R.id.bt_select);
        tvUri = findViewById(R.id.tv_uri);
        tvPath = findViewById(R.id.tv_path);
  
        // Initialize result launcher
        resultLauncher = registerForActivityResult(
            new ActivityResultContracts
                .StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(
                    ActivityResult result)
                {
                    // Initialize result data
                    Intent data = result.getData();
                    // check condition
                    if (data != null) {
                        // When data is not equal to empty
                        // Get PDf uri
                        Uri sUri = data.getData();
                        // set Uri on text view
                        tvUri.setText(Html.fromHtml(
                            "<big><b>PDF Uri</b></big><br>"
                            + sUri));
  
                        // Get PDF path
                        String sPath = sUri.getPath();
                        // Set path on text view
                        tvPath.setText(Html.fromHtml(
                            "<big><b>PDF Path</b></big><br>"
                            + sPath));
                    }
                }
            });
  
        // Set click listener on button
        btSelect.setOnClickListener(
            new View.OnClickListener() {
                @Override public void onClick(View v)
                {
                    // check condition
                    if (ActivityCompat.checkSelfPermission(
                            MainActivity.this,
                            Manifest.permission
                                .READ_EXTERNAL_STORAGE)
                        != PackageManager
                               .PERMISSION_GRANTED) {
                        // When permission is not granted
                        // Result permission
                        ActivityCompat.requestPermissions(
                            MainActivity.this,
                            new String[] {
                                Manifest.permission
                                    .READ_EXTERNAL_STORAGE },
                            1);
                    }
                    else {
                        // When permission is granted
                        // Create method
                        selectPDF();
                    }
                }
            });
    }
  
    private void selectPDF()
    {
        // Initialize intent
        Intent intent
            = new Intent(Intent.ACTION_GET_CONTENT);
        // set type
        intent.setType("application/pdf");
        // Launch intent
        resultLauncher.launch(intent);
    }
  
    @Override
    public void onRequestPermissionsResult(
        int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(
            requestCode, permissions, grantResults);
  
        // check condition
        if (requestCode == 1 && grantResults.length > 0
            && grantResults[0]
                   == PackageManager.PERMISSION_GRANTED) {
            // When permission is granted
            // Call method
            selectPDF();
        }
        else {
            // When permission is denied
            // Display toast
            Toast
                .makeText(getApplicationContext(),
                          "Permission Denied",
                          Toast.LENGTH_SHORT)
                .show();
        }
    }
}


Here is the final output of our application.

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads