Open In App

How to Retrieve PDF File From Firebase Realtime Database in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

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 which 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 are going to build in this article?

We will be creating two Activities in this project. In one activity there will e a single Button and in another activity, we are viewing the pdf file. So when the user will click on the Button an AlertBox will be shown with there options “Download“, “View“, and “Cancel“. So the user will choose whether he/she want 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

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’

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.

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

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

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

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: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

Please refer to How to Create New Activity in Android Studio and name the activity as ViewpdfActivity. This activity is used for viewing the pdf file. 

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: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:



Last Updated : 09 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads