Canvas - null pointer exception

无人久伴 提交于 2020-01-06 06:41:07

问题


Sometimes, I am getting NullPointerException in the line. Please let me know how to correct this. At the time of error, I have checked the possibility for the null value in variable backgoundImage. The variable backgoundImage is not null.

  canvas.drawBitmap(backgoundImage, 0, 0    , null);

Code:

    @Override
    public void run() {
        // TODO Auto-generated method stub
        ourHolder = getHolder();
        while (isRunning) { 
            if (!ourHolder.getSurface().isValid()){
                continue;
            } 
            canvas = ourHolder.lockCanvas();    
            screenCenterX = dWidth / 2; 
            screenCenterY = dHeight / 2;  

            //-----------------------------------------------------------------------------------
            if(backgoundImage == null){ 
                try { 
                    Log.i("DragDropCheck", "----------------backgoundImage is null--------");
                    backgoundImage = getAssetImage(getContext(),"backgroundhomepage");
                    canvas.drawBitmap(backgoundImage, 0, 0  , null); 
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            }else{ 
                canvas.drawBitmap(backgoundImage, 0, 0  , null);
            } 
            //-----------------------------------------------------------------------------------

            if (imagePublishDone) {
                if(!welcomeDone){                       
                 welcomeDone=true;
                }
                moveImageInEllipticalPath();
            } else {
                initialImagePublish();
            } 
            centreReached = false;
            ourHolder.unlockCanvasAndPost(canvas);
        }
    } 

logcat:

07-09 22:40:18.689: E/AndroidRuntime(8794): FATAL EXCEPTION: Thread-621
07-09 22:40:18.689: E/AndroidRuntime(8794): java.lang.NullPointerEception
07-09 22:40:18.689: E/AndroidRuntime(8794): at com.eample.funandlearn.DragDrop$MyBringBackSurface.run(DragDrop.java:645)
07-09 22:40:18.689: E/AndroidRuntime(8794): at java.lang.Thread.run(Thread.java:856)

回答1:


Probably, the problem is that the canvas variable is null. You should manage that specific case to avoid executing code when the ourHolder.lockCanvas() call returns null (also, you should check that your ourHolder variable isn't null before executing the while loop).



来源:https://stackoverflow.com/questions/17554452/canvas-null-pointer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!