📌  相关文章
📜  如何使用Firebase在Android中创建动态PDF查看器?

📅  最后修改于: 2021-05-13 15:44:33             🧑  作者: Mango

如果您要为学生或教育目的创建应用程序,则需要添加一些PDF文件以在我们的应用程序中显示一些数据。这些PDF文件会定期更新。为了从服务器加载此PDF,我们更喜欢使用PDF Viewer,它将从Android中的URL加载PDF。在其中,我们在Apps代码内添加PDF的URL并从该URL加载它。如果我们想更改该PDF,该怎么办,为此,我们需要在代码内更改PDF的URL。但实际上,将无法更改PDF文件的URL并为用户更新该应用程序。因此,为了处理这种情况,我们将使用Firebase。通过使用Firebase,我们将动态地从Firebase加载PDF并在我们的应用程序内部更新PDF。现在,我们将转向实施部分。

我们将在这个项目中建立什么?

我们将构建一个应用程序,在该应用程序中,我们将从Firebase控制台加载PDF,并通过更改Firebase控制台中的URL实时更新该PDF。为了实施该项目,我们将使用Firebase实时数据库,通过该数据库我们将实时更新PDF。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将您的应用连接到Firebase

创建新项目后。导航到顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase实时数据库。单击该选项,您将在“将应用程序连接到Firebase”和“将Firebase实时数据库添加到您的应用程序”中看到两个选项。单击立即连接,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。

完成此过程后,您将看到以下屏幕。

现在,验证您的应用是否已连接到Firebase。转到您的build.gradle文件。导航至应用程序> Gradle脚本> build.gradle文件,并确保在依赖项部分中添加了以下依赖项。

添加此依赖性后,在您的Gradle文件中添加PDF Viewer的依赖性。

步骤3:在build.gradle文件中添加PDF Viewer的依赖项

导航到应用程序> Gradle脚本> build.gradle文件,然后在其中添加以下依赖项。

添加此依赖项后,同步您的项目。现在,我们将转向XML部分。

步骤4:在您的AndroidManifest.xml文件中添加互联网权限

在AndroidManifest.xml文件中添加Internet权限。

XML


XML


  
    
    
  


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 RetrivePdfFromFirebase
                // class which will load our PDF file.
                new RetrivedPdffromFirebase().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 RetrivedPdffromFirebase extends AsyncTask {
        // 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();
        }
    }
}


步骤5:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  

步骤6:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

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 RetrivePdfFromFirebase
                // class which will load our PDF file.
                new RetrivedPdffromFirebase().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 RetrivedPdffromFirebase extends AsyncTask {
        // 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();
        }
    }
}

第7步:在Firebase控制台中添加PDF的URL

用于在Firebase控制台中添加PDF URL。在浏览器中浏览Firebase,然后单击右上角的“转到控制台”选项,如以下屏幕截图所示。

单击“转到控制台”选项后,您将看到您的项目。从可用的项目列表中单击您的项目名称。

单击项目后。单击左侧窗口中的实时数据库选项。

单击此选项后,您将看到右侧的屏幕。在此页面上,单击顶部栏中的“规则”选项。您将看到以下屏幕。

在此项目中,我们添加了适用于读取和写入的规则,因为我们没有使用任何身份验证来验证用户。因此,我们目前将其设置为true以测试我们的应用程序。更改规则后。单击右上角的“发布”按钮,您的规则将保存在此处。现在再次回到“数据”选项卡。现在,我们将从Firebase本身将数据手动添加到Firebase。

步骤8:在Firebase控制台中为PDF添加URL

在Firebase实时数据库中。导航到“数据”选项卡。在此选项卡中,单击数据库中的“ Hower on Database”部分,然后单击“ +”图标。单击“ +”图标后,您将看到两个输入字段,即“名称”和“值”字段。在“名称”字段中,您必须为PDF文件添加一个引用,在本例中为“ url”。在我们的值字段中,我们必须为我们的PDF文件添加一个URL。在此字段中添加值之后。单击添加按钮,您的数据将被添加到Firebase控制台。

添加此PDF URL后,现在运行您的应用程序并查看应用程序的输出。

输出:

您可以更改PDF的URL,并且应用程序内部的PDF将实时更新,而无需再次加载应用程序。

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!