How to Retrieve PDF File From Firebase Realtime Database in Android?
Last Updated :
07 Aug, 2024
When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is its Firebase Realtime Database.
By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. We will be creating our storage bucket and we can insert our pdf there and get it directly into our app.
What We Will Build
We will be creating two Activities in this project. In one activity there will be a single Button and in another activity, we are viewing the pdf file. So when the user clicks on the Button an AlertBox will be shown with the options "Download", "View", and "Cancel". So the user will choose whether he/she wants to View or Download the pdf. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
Step 2: Connect your app to Firebase
- After creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.

- Inside that column navigate to Firebase Realtime Database. Click on that option and you will get to see two options on
- Connect app to Firebase and,
- Add Firebase Realtime Database to your app.
- Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.

- After completing this process you will get to see the below screen.

- Now verify that your app is connected to Firebase or not. Go to your build.gradle file. After this, navigate to:
- app -> Gradle Scripts -> build.gradle file
- Make sure that the below dependency is added in your dependencies section.
implementation ‘com.google.firebase:firebase-database:19.6.0’
- If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app. Also, add the following dependency.
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
- Now sync the project from the top right corner option of 'Sync now'.
Step 3: Add Internet permission in the AndroidManifest.xml file
Navigate to the 'AndroidManifest.xml' file and add the below permission for getting internet permission in the app.
Step 4: Working with the activity_main.xml file
- Go to the 'activity_main.xml' file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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">
<!--We will click on it to view pdf-->
<Button
android:id="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@color/black"
android:padding="10dp"
android:text="Click here to View pdf "
android:textSize="10dp" />
</LinearLayout>
Step 5: Working with the MainActivity.java file
- 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
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
Button view;
DatabaseReference database;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.view);
// Initialising the reference to database
database = FirebaseDatabase.getInstance().getReference().child("pdf");
database.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// getting a DataSnapshot for the location at the specified
// relative path and getting in the link variable
message = dataSnapshot.getValue(String.class);
}
// this will called when any problem
// occurs in getting data
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// we are showing that error message in toast
Toast.makeText(MainActivity.this, "Error Loading Pdf", Toast.LENGTH_SHORT).show();
}
});
// After clicking here alert box will come
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
CharSequence options[] = new CharSequence[]{
"Download",
"View",
"Cancel"
};
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Choose One");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// we will be downloading the pdf
if (which == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(message));
startActivity(intent);
}
// We will view the pdf
if (which == 1) {
Intent intent = new Intent(v.getContext(), ViewPdfActivity.class);
intent.putExtra("url", message);
startActivity(intent);
}
}
});
builder.show();
}
});
}
}
Step 6: Create a new ViewpdfActivity class
Step 7: Working with the activity_view_pdf.xml file
- Navigate to the app > res > layout > activity_view_pdf.xml and add the below code to that file. Below is the code for the 'activity_view_pdf.xml' file.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPdfActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/abc"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step 8: Working with the ViewpdfActivity.java file
- Go to the 'ViewpdfActivity.java' file and refer to the following code. Below is the code for the ViewpdfActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ViewPdfActivity extends AppCompatActivity {
String urls;
PDFView pdfView;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pdf);
pdfView = findViewById(R.id.abc);
// Firstly we are showing the progress
// dialog when we are loading the pdf
dialog = new ProgressDialog(this);
dialog.setMessage("Loading..");
dialog.show();
// getting url of pdf using getItentExtra
urls = getIntent().getStringExtra("url");
new RetrivePdfStream().execute(urls);
}
// Retrieving the pdf file using url
class RetrivePdfStream extends AsyncTask<String, Void, InputStream> {
@Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
// adding url
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// if url connection response code is 200 means ok the execute
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
}
// if error return null
catch (IOException e) {
return null;
}
return inputStream;
}
@Override
// Here load the pdf and dismiss the dialog box
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
dialog.dismiss();
}
}
}
Step 9: Adding pdf on firebase storage and copy the link of that pdf
- In firebase go to the Storage option then click on Get Started button.

- After that click on the Upload file option to insert a pdf on firebase storage.

- After that click on the pdf that you inserted then the from pdf details come in the right section then click on the access token and copy the pdf URL.

Step 10: Add that pdf URL to the real-time database
- Go to the Realtime database option then add these values to the database. Inside that screen click on Realtime Database in the left window.

- After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.

In this project, we are adding our rules as true for reading as well as a write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules.
Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself. Inside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the “+” option on the right side and click on that option. After clicking on that option. Add the data as added in the below image.
Make sure to add “pdf” in the Name field because we are setting our reference for Firebase as “pdf”. So we have to set it to “pdf”. You can change your reference and also change it in the Database. Inside the value field, paste the copied pdf url. This will be the string which we are going to display inside our pdfview. After adding data click on the add button and your data will be added in Firebase and this data will be displayed in your app.

Output:
Similar Reads
Firebase - Introduction Firebase, a product of Google, is a powerful platform that enables developers to build, manage, and scale applications with ease. It simplifies app development by offering a secure and efficient backend, eliminating the need for server-side programming. Firebase supports multiple platforms, includin
7 min read
Firebase Tutorial Firebase is a comprehensive app development platform provided by Google. It offers a suite of tools and services that help developers build, deploy, and grow their mobile(Android/IOS) and web applications quickly and efficiently. The key features of Firebase include a real-time database, authenticat
8 min read
Firebase Realtime Database Firebase Realtime Database is a powerful NoSQL cloud database that enables real-time data storage and synchronization across all clients. It's particularly suited for applications requiring live updates, such as chat apps and collaborative tools. By following the setup instructions and using the pro
7 min read
How to Deploy React project on Firebase? When developing any project we must host it somewhere so that the whole world can see our hard-work. Hosting websites can be hectic sometimes, but you don't need to worry as we can now host our React project on Firebase within a minute or two with a very simple setup. The Steps to deploy react proje
2 min read
What is Firebase Authentication Firebase Authentication is a powerful backend service offered by Google Firebase, designed to speed up the user authentication process in applications. Supporting various authentication methods, such as email/password, phone number, and social logins, Firebase Authentication ensures secure user auth
4 min read
Firebase vs AWS - Best Backend Solution for App Development in 2025 Choosing the best backend solution is the first step in building a successful web or mobile app. Among the two prime competitors, Firebase (Google) and Amazon Web Services (AWS), that appear during the cloud computing period, there lies a great deal of power. Both platforms offer powerful tools to h
10 min read
Login and Registration in Android using Firebase in Kotlin Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. In this article, we will learn the
4 min read
Firebase Authentication with Phone Number OTP in Flutter Web Phone number verification using Firebase in the Flutter Web app can be done by sending OTP SMS to the phone number. The user will enter the OTP in the message and will easily sign in to his/her account. We are going to implement it in Flutter Web. Step by Step implementation Step 1: Create a new Flu
4 min read
Hosting A Static Website On Firebase For Free Building a web application is always a time-consuming job, especially for the beginner developers who have just landed their feet in the vast world of programming. And one of the most exciting parts is when the application is available for all to see. Being a new bee in programming most beginners la
5 min read
Why Use Firebase ? Firebase is a platform provided by Google to develop Android and web applications. It provides a user-friendly experience for building full stack applications. It also provides databases, authentications, storage for files, and many more such kinds of facilities. As stated earlier, it is a platform
6 min read