Canvas - 空指针异常

时间:2013-07-09 17:23:28

标签: android android-canvas android-image

有时,我在行中收到NullPointerException。请让我知道如何纠正这个问题。在出错时,我检查了变量backgoundImage中null值的可能性。变量backgoundImage不为null。

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

代码:

    @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 个答案:

答案 0 :(得分:0)

问题可能是canvas变量为null。您应该管理该特定情况,以避免在ourHolder.lockCanvas()调用返回null时执行代码(同样,在执行ourHolder之前,您应该检查您的while变量是否为空循环)。