How to Implement PDF Picker in Android?
Last Updated :
04 May, 2025
In this article, we are going to see how we can implement a PDF picker in android studio and get the file information of the pdf like file name, size and path. In this application, we will create a launcher to launch the file picker and display the file information after a pdf is picked successfully.
Note that we are going to implement this application using Java & Kotlin language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in the Android Studio, please refer to How to Create/Start a New Project in Android Studio?
Step 2: Working with activity_main.xml
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. In this file we will be adding a button to launch pdf picker and a textview to display the document informations.
activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Button to pick pdf-->
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick pdf"/>
<!--TextView to display file information-->
<TextView
android:id="@+id/fileNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="32dp"
android:text="file name"/>
</LinearLayout>
Step 3: Working with MainActivity file
Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail
MainActivity.java
package org.geeksforgeeks.demo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
// UI elements
private Button button;
private TextView fileNameTextView;
// URI for the selected PDF
private Uri selectedPdfUri;
// Activity launcher for picking PDF
private final ActivityResultLauncher<String[]> pickPdfLauncher =
registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> {
if (uri != null) {
selectedPdfUri = uri;
// Get the file information
Pair<String, Long> fileInfo = getFileInfo(uri);
String fileName = fileInfo.first;
float fileSize = fileInfo.second;
// Convert file size to MB
String fileSizeInMB = String.format(Locale.getDefault(), "%.3f", fileSize / 1000000.0);
// Update the UI with the file information
fileNameTextView.setText("Filename - " + fileName + "\nFile size - " + fileSizeInMB + " MB\nFile path - " + uri.getPath());
} else {
// Handle the case where no file was selected
Toast.makeText(MainActivity.this, "No file selected", Toast.LENGTH_SHORT).show();
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI elements
button = findViewById(R.id.button);
fileNameTextView = findViewById(R.id.fileNameTextView);
// Set click listener for the button
button.setOnClickListener(v -> {
// Launch the PDF picker
pickPdfLauncher.launch(new String[]{"application/pdf"});
});
}
// Function to get the file name from URI - optional
private Pair<String, Long> getFileInfo(Uri uri) {
// Initialize default values
String fileName = "Unknown";
long fileSize = 0L;
// Query the content resolver to get the file name and size
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
try {
// Move to the first row
if (cursor.moveToFirst()) {
// Get the display name and size columns
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// Check if the columns exist
if (nameIndex != -1) {
// Get the file name and size
fileName = cursor.getString(nameIndex);
fileSize = cursor.getLong(sizeIndex);
}
}
} finally {
cursor.close();
}
}
// Return the file name and size as a pair
return new Pair<>(fileName, fileSize);
}
// Simple Pair class
private static class Pair<F, S> {
public final F first;
public final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
}
MainActivity.kt
package org.geeksforgeeks.demo
import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import java.lang.String.format
class MainActivity : AppCompatActivity() {
// UI elements
private lateinit var button: Button
private lateinit var fileNameTextView: TextView
// URI for the selected PDF
private var selectedPdfUri: Uri? = null
// Activity launcher for picking PDF
private val pickPdfLauncher =
registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
uri?.let {
selectedPdfUri = it
// Get the file information
val fileInfo = getFileInfo(it)
val fileName = fileInfo.first
val fileSize = fileInfo.second.toFloat()
// Convert file size to MB
val fileSizeInMB = format("%.3f", fileSize / 1000000.0)
// Update the UI with the file information
fileNameTextView.text = "Filename - $fileName\nFile size - $fileSizeInMB MB\nFile path - ${it.path}"
} ?: run {
// Handle the case where no file was selected
Toast.makeText(this@MainActivity, "No file selected", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize UI elements
button = findViewById(R.id.button)
fileNameTextView = findViewById(R.id.fileNameTextView)
// Set click listener for the button
button.setOnClickListener {
// Launch the PDF picker
pickPdfLauncher.launch(arrayOf("application/pdf"))
}
}
// Function to get the file name from URI - optional
private fun getFileInfo(uri: Uri): Pair<String, Long> {
// Initialize default values
var fileName = "Unknown"
var fileSize = 0L
// Query the content resolver to get the file name and size
contentResolver.query(uri, null, null, null, null)?.use { cursor ->
// Move to the first row
if (cursor.moveToFirst()) {
// Get the display name and size columns
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
// Check if the columns exist
if (nameIndex != -1) {
// Get the file name and size
fileName = cursor.getString(nameIndex)
fileSize = cursor.getLong(sizeIndex)
}
}
}
// Return the file name and size as a pair
return Pair(fileName, fileSize)
}
}
Output:
Similar Reads
How to Implement Polling in Android? Many times you may have seen on some apps like youtube, LinkedIn, etc. polling is done and users choose their options whatever they want to choose. Here we are going to implement polling in Android Studio. What we are going to build in this article? In this article, we will ask the user a question a
4 min read
How to Implement Date Range Picker in Android? Date Range Picker is a widely used feature in many popular Android apps and an essential component of Material Design. It allows users to select a range of dates such as a start and end date for various purposes including scheduling, filtering data, and setting time boundaries. Some Of The Real Life
4 min read
How to Implement Item Click Interface in Android? When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. What we are going to build in this article?In this article, we will be usin
5 min read
How to Implement Custom Searchable Spinner in Android? Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the c
5 min read
How to Implement Shapeable ImageView in Android? In Android, ShapeableImageView is used to change the shape of your image to circle, diamond, etc. Also, you can set a corner radius to your ImageView. You can do much more by using this ShapeableImageView with minimal code. So in this article, we are going to make a ShapableImageView in android. By
5 min read