Open In App

How to Create Dynamic PDF Viewer in Android with Firebase?

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Android. Inside this, we add the URL for PDF inside our Apps code and load it from that URL. What if we want to change that PDF, so for that we need to change the URL of the PDF inside our code. But practically it will not be possible to change the URL for PDF files and update the app for users. So for handling this case we will use Firebase. By using Firebase we will dynamically load PDF from Firebase and update the PDF inside our app. Now we will move towards the implementation part. 

What we are going to build in this project? 

We will be building an application in which we will be loading PDF from our Firebase Console and update that PDF in Realtime by changing the URL in our Firebase Console. For the implementation of this project, we will be using Firebase Realtime Database with which we will be updating our PDF in Realtime. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

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. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section. 

implementation ‘com.google.firebase:firebase-database:19.6.0’

After adding this dependency add the dependency of PDF Viewer in your Gradle file. 

Step 3: Add the dependency for PDF Viewer in build.gradle file

Navigate to the app > Gradle Scripts > build.gradle file and add below dependency in it. 

implementation ‘com.github.barteksc:android-pdf-viewer:2.8.2’

After adding this dependency sync your project. Now we will move towards our XML part. 

Step 4: Add internet permission in your AndroidManifest.xml file

Add the permission for the internet in the AndroidManifest.xml file. 

XML




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


Step 5: 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"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--PDF View for displaying our PDF-->
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</RelativeLayout>


Step 6: 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.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
import com.github.barteksc.pdfviewer.PDFView;
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;
 
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity {
 
    // creating a variable for our Firebase Database.
    FirebaseDatabase firebaseDatabase;
     
    // creating a variable for our Database
    // Reference for Firebase.
    DatabaseReference databaseReference;
     
    // creating a variable for our pdfview
    private PDFView pdfView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing variable for pdf view.
        pdfView = findViewById(R.id.pdfView);
         
        // below line is used to get the instance
        // of our Firebase database.
        firebaseDatabase = FirebaseDatabase.getInstance();
         
        // below line is used to get reference for our database.
        databaseReference = firebaseDatabase.getReference("url");
         
        // calling method to initialize
        // our PDF view.
        initializePDFView();
    }
 
    private void initializePDFView() {
 
        // calling add value event listener method
        // for getting the values from database.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                // this method is call to get the realtime updates in the data.
                // this method is called when the data is changed in our Firebase console.
                // below line is for getting the data from snapshot of our database.
                String pdfUrl = snapshot.getValue(String.class);
                 
                // after getting the value for our Pdf url we are
                // passing that value to our RetrievePdfFromFirebase
                // class which will load our PDF file.
                new RetrievedPdffromFirebase().execute(pdfUrl);
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // calling on cancelled method when we receive
                // any error or we are not able to get the data.
                Toast.makeText(MainActivity.this, "Fail to get PDF url.", Toast.LENGTH_SHORT).show();
            }
        });
    }
 
 
    class RetrievedPdffromFirebase extends AsyncTask<String, Void, InputStream> {
        // we are calling async task and performing
        // this task to load pdf in background.
        @Override
        protected InputStream doInBackground(String... strings) {
            // below line is for declaring
            // our input stream.
            InputStream pdfStream = null;
            try {
                // creating a new URL and passing
                // our string in it.
                URL url = new URL(strings[0]);
                 
                // creating a new http url connection and calling open
                // connection method to open http url connection.
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                if (httpURLConnection.getResponseCode() == 200) {
                    // if the connection is successful then
                    // we are getting response code as 200.
                    // after the connection is successful
                    // we are passing our pdf file from url
                    // in our pdfstream.
                    pdfStream = new BufferedInputStream(httpURLConnection.getInputStream());
                }
 
            } catch (IOException e) {
                // this method is
                // called to handle errors.
                return null;
            }
            // returning our stream
            // of PDF file.
            return pdfStream;
        }
 
        @Override
        protected void onPostExecute(InputStream inputStream) {
            // after loading stream we are setting
            // the pdf in your pdf view.
            pdfView.fromStream(inputStream).load();
        }
    }
}


Step 7: Adding URL for PDF in your Firebase Console

For adding PDF URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot. 

 After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects. 

After clicking on your project. Click on the Realtime Database option 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 read 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.

Step 8: Adding URL for your PDF in Firebase Console

Inside Firebase Realtime Database. Navigate to the Data tab. Inside this tab Hover on database section inside that click on the “+” icon. After clicking on the “+” icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add a reference for your PDF file which in our case is “url”. And in our value field, we have to add a URL for our PDF file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console. 

After adding this PDF URL now run your app and see the OUTPUT of your app. 

Output: 

You can change the URL of the PDF and the PDF inside your app will be updated in Realtime without loading your app again. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads