Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView not showing image from bitmap created by PDFRenderer on Android API 29

I have a PDF that I want to show in an ImageView. It's showing on API 24-28 but no image shows on API 29. I think the issue may be the bitmap created by the PDFRenderer.

I put a breakpoint after the .render method and (in the debugger) clicked "View Bitmap" here: Click "View Bitmap

On API 29, I sometimes get the image, and sometimes I get this error:

Error while evaluating expression, Object has been collected

Preview of bitmap

On API 24-28, I do not get this error. I always get the image.

Below is the sample code:

        File file = new File(getExternalFilesDir(null), "fileName.pdf");
        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
        if (currentPage < 0) {
            currentPage = 0;
        } else if (currentPage > renderer.getPageCount()) {
            currentPage = renderer.getPageCount() - 1;
        }
        Bitmap bitmap = Bitmap.createBitmap(800, 1000, Bitmap.Config.ARGB_8888);
        Rect rect = new Rect(0, 0, 800, 1000);
        PdfRenderer.Page page = renderer.openPage(currentPage);
        page.render(bitmap, rect, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        page.close();
        renderer.close();
        image.setImageBitmap(bitmap);
        image.invalidate();

Does anyone know why the image is always showing on API 24-28 but not on API 29?

like image 438
mobiledevcookie Avatar asked Nov 06 '22 11:11

mobiledevcookie


1 Answers

I ran into this on API 30 also. It looks garbage collection may be more aggressive now for bitmaps. I solved this by changing the scope of the problem bitmap from private to public and setting it to null when the relevant view is destroyed.

like image 200
Robert Strauss Avatar answered Nov 14 '22 22:11

Robert Strauss