Search code examples
javaandroidnullpointerexceptionrunnable

post runnable() resulting in nullpointerexcepion why?


i am using this technique shown below because I have to wait before the view is created before I can get the width and height. or it will result in a nullpointerexcepion.

so I used example 1 below and it works perfectly by posting a runnable to a frameLayout so that after frameLayout is created it will get the width and height.

but for example 2 it does not work and results in a nullpointer exception, since both techniques are the same what is wrong? is there a better way to do this?

exmaple 1, works with no problems

 frameLayoutOne = (FrameLayout) findViewById(R.id.frameLayout1);

 frameLayoutOne.post(new Runnable(){
        public void run(){
          widthofit = frameLayoutOne.getWidth();
          heightofit = frameLayoutOne.getHeight();
          Toast.makeText(MainActivity.this, "width 1 is: " + widthofit , Toast.LENGTH_SHORT).show();
          Toast.makeText(MainActivity.this, "height 1 is: " + heightofit , Toast.LENGTH_SHORT).show();

        }
    });

example 2, results in nullpointerexception

 ViewGroup contentViewObj = (ViewGroup) getContentView();

 contentViewObj.post(new Runnable(){ // <-- NULL POINTER ON THIS LINE
        public void run(){
             final ActionBar actionBar = getActionBar();
                if(actionBar!=null){
                     if(actionBar.isShowing()) {
                        int actionBarHeightNow = actionBar.getHeight();
                             Toast.makeText(MainActivity.this, "total   height of actionbar currently: " + actionBarHeightNow, Toast.LENGTH_LONG).show();
                     } else {
                         Toast.makeText(MainActivity.this, "actionBar is not showing version 1", Toast.LENGTH_LONG).show();
                     }
                     } else {
                            Toast.makeText(MainActivity.this, "actionBar is not showing version 2", Toast.LENGTH_LONG).show();
                     }

        }
    }); 

Solution

  • If you need to wait for a layout to get width and height of a View I wouldn't use a runnable but a GlobalLayoutListener, check this question for details.