Search code examples
javaandroidpdfassets

AndroidPDFViewer - Can not open pdf document in my application


I am using this library. I am trying to load a PDF located in assets & it does not load. Here is where I load it:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;

public class MainActivity extends AppCompatActivity {

    private PDFView pdfView;
    private String nameOfPDF = "" + R.string.name_of_pdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView = (PDFView) findViewById(R.id.pdfView);

        pdfView.fromAsset(nameOfPDF).load();
    }
}

And here is the relevant XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ru.webant.projects.mypdfviewer.MainActivity">

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Application is run but nothing happens. Why is this happening?


Solution

  • Because you are not setting the correct filename. Look here:

    private String nameOfPDF = "" + R.string.name_of_pdf;
    

    This results in : nameOfPDF = SomeIdAsString. What you want to call is getString() like so:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        pdfView = (PDFView) findViewById(R.id.pdfView);
    
        pdfView.fromAsset(getString(R.string.name_of_pdf)).load();
    }