0

I get the error java.lang.IllegalArgumentException: width and height must be > 0 and I think this error may be caused by the webview. I am trying to display a rendered PDF file in a webview and there are some files which work fine but others launch this error.

activity_convert.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>

onCreate method:

//Setup webview
    wv = (WebView)findViewById(R.id.webView1);
    wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
    wv.getSettings().setSupportZoom(true);//allow zoom
    //get the width of the webview

    wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            ViewSize = wv.getWidth();
            //ViewSize = wv.getHeight();
            System.out.println("webView: " + wv.getWidth());
            System.out.println("webView: " + wv.getHeight());
            wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });

PDF render:

//create pdf document object from bytes
ByteBuffer bb = ByteBuffer.NEW(data);
PDFFile pdf = new PDFFile(bb);
//Get the first page from the pdf doc
PDFPage PDFpage = pdf.getPage(1, true);
//create a scaling value according to the WebView Width
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
//convert the page into a bitmap with a scaling value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true)

I have been reading several posts here with the same problem but their solutions don't work for my code. I've tried to get the width and height parameters but I can't figure out why this doesn't work.

1 Answers1

0

the problem is with ViewTreeObserver. You are trying to get width and height of an elements, that weren't drawn yet.

In short, the views are not built yet in onCreate(), onStart(), or onResume(). Since they technically don't exist (as far as the ViewGroup is concerned), their dimensions are 0.

In long, you can go here for a better explanation on how to handle it.

How do you to retrieve dimensions of a view? getHeight() and getWidth() always return zero

I recommend you to try DisplayMetrics to get the Height and width..

like this

Community
  • 1
  • 1
King of Masses
  • 18,405
  • 4
  • 60
  • 77