3

I'm a beginner developer, and it’s my first question post ever.

My app presents a PDF e-book, I used this library:

com.github.barteksc:android-pdf-viewer:2.8.2

When I reopen my app, pdfView loads the first page “pageNumber=0”, I want it to load the last page I left it.

I found most solutions were presented for this issue on SO, but nothing worked for me.

I think there is a simple solution, such as using:

SavedPage = pdfView.getCurrentPage() inside onSavedInstanceState, then restoring that integer inside onCreate.

But I don’t know how to do this. So it would be kind of you to guide me to the simplest way to make my pdfView load the last page I was reading.

Here is the code of my Reading Activity:

package com.turquoise.jeebalalhasanat;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;

public class ReadingActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener {

    private static final String TAG = ReadingActivity.class.getSimpleName();
    public static final String PDF_FILE = "my_book.pdf";

    PDFView pdfView ;
    Integer pageNumber;
    String pdfFileName;

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

        pdfView = (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(PDF_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(PDF_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
        }

    @Override
    public void onPageChanged(int page, int pageCount) {

        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));

    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

Any help is appreciated!

Harsha pps
  • 2,012
  • 2
  • 25
  • 35
TA.Fayrouz
  • 61
  • 9

3 Answers3

3

Thank God, I reached to a solution! Android Developer Documentation of Google will remain developer’s best friend.

I would like to share it, to help every beginner developer who needs help about this issue.

So here is how to restore the last page you load in a PDF View: First step: declare an Integer variable inside your activity:

Integer savedPage;

Second step: inside onStop():

@Override
protected void onStop() {
    super.onStop();


savedPage = pdfView.getCurrentPage();

\\ create a shared preference file

    SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);


\\ to write to this shared preference file

    SharedPreferences.Editor myEditor = mySharedPreferences.edit();



\\ store the page number you left it 

    myEditor.putInt("retrievedPage",savedPage);



\\ to save changes

 myEditor.apply();



}

Third step: inside onCreate():

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


\\ To retrieve the  number of the last page from your shared preferences file

 SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);

savedPage = mySharedPreferences.getInt("retrievedPage",0);

    pageNumber = savedPage;
}

Here is the full activity code:

import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;






public class ReadingActivity extends Activity  implements OnPageChangeListener,OnLoadCompleteListener {


    private static final String TAG = ReadingActivity.class.getSimpleName();
    public static final String PDF_FILE = "my_book.pdf";


    PDFView pdfView ;
    Integer pageNumber;
    String pdfFileName;

Integer currentPageNumber;
Integer savedPage;







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






SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);

savedPage = mySharedPreferences.getInt("retrievedPage",0);

pageNumber = savedPage;







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


    }










    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(PDF_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();




        }





    @Override
    public void onPageChanged(int page, int pageCount) {

        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));

            }




    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }


    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }



@Override
protected void onStop() {
    super.onStop();

    SharedPreferences mySharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor myEditor = mySharedPreferences.edit();


savedPage = pdfView.getCurrentPage();
myEditor.putInt("retrievedPage",savedPage);
myEditor.apply();


}

}

Now you should achieve your goal. Happy coding ^^!

TA.Fayrouz
  • 61
  • 9
  • 2
    This works perfectly if I have only one book. What if I have multiple books in single application and how to restore pages for those books. I tried to use HashSet to save pagenumbers in SharedPreferences but did not work. Was able to retrieve last read page only for one book. Any help is greatly appreciated. – WIT_NGU Dec 07 '20 at 11:09
  • I also need animation to appear when loading current page as default page. I cannot find where to set this, what I want is that scroll animation appears as opened pdf goes to last read page. any help is greatly appreciated. – WIT_NGU Dec 08 '20 at 09:06
2

This works perfectly if I have only one book. What if I have multiple books in single application and how to restore pages for those books ? I found the prefect answer to this problem By using this code in OnpageChanged Method

   SharedPreferences.Editor editor = getSharedPreferences("shared", MODE_PRIVATE).edit();
    switch(BookId){
        case 1:
            arr[0]=page;
            setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
            editor.putInt("id1", arr[0]);
            editor.apply();
            break;

    case 2:
        arr[1]=page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
        editor.putInt("id2", arr[1]);
        editor.apply();
            break;


//add cases as the numbers of Books or use ( for Loop )
}

this worked with me ,any question comment and I will answer

0

for multiple books, you need to have unique identifiers of each book. If the book title is unique, you can use it. otherwise you'd have to have an id for the book.

After getting the ID, you need to use that as key when saving the page number into shared preferences. This allows you to simply use the unique identifier to query the last saved page from shared preferences.

Ziyaad Shiraz
  • 144
  • 2
  • 7