Skip to content

Using PDFViewer in ViewPager and swiping away before PDF loads causes NPE crash #1256

@Zhuinden

Description

@Zhuinden
Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'boolean java.lang.Thread.isAlive()' on a null object reference
com.github.barteksc.pdfviewer.PDFView.loadComplete (PDFView.java:756)
com.github.barteksc.pdfviewer.DecodingAsyncTask.onPostExecute (DecodingAsyncTask.java:80)
com.github.barteksc.pdfviewer.DecodingAsyncTask.onPostExecute (DecodingAsyncTask.java:27)
android.os.AsyncTask.finish (AsyncTask.java:771)

com.android.internal.os.ZygoteInit.main (ZygoteInit.java:961)

I'm a little behind on schedule so I don't have a few months to wait for a fix, so this is how I fixed it

    /** Called when the PDF is loaded */
    void loadComplete(PdfFile pdfFile) {
        state = State.LOADED;

        this.pdfFile = pdfFile;

        if (renderingHandlerThread == null || !renderingHandlerThread.isAlive()) {
            if(renderingHandlerThread == null) {
                renderingHandlerThread = new HandlerThread("PDF renderer");
            }
            renderingHandlerThread.start();
        }

The real problem though is that onDetachedFromWindow kills the RenderingThread and sets it to null, but there is no onAttachedToWindow counterpart. If you swipe away in a ViewPager before the PDF loads, then the render thread will be destroyed. In fact, I'm guessing just swiping away swiping back swiping away swiping back would also crash as the RenderThread is destroyed but never re-created

So I also added this

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (renderingHandlerThread == null) {
             renderingHandlerThread = new HandlerThread("PDF renderer");
        }
    }

This fixes the crash entirely 100% of the time. It was causing a crash for 8% of users. :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions