问题
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