我正在解码位图并在画布背景中使用图像。当我使用解码的图像绘制背景时,我得到了空指针异常。请指出我的代码需要更正的地方。
以下是我用于解码的代码
public Bitmap getAssetImage(Context context, String filename) throws IOException {
AssetManager assets = getApplicationContext().getResources().getAssets();
InputStream buffer = null;
try {
buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(buffer,null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH= (int) dWidth;
final int REQUIRED_HIGHT= (int) dHeight;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(buffer, null, o2);
}
public void run() {
// TODO Auto-generated method stub
// Log.i("Notice", "In run of mybringback");
if(backgoundImage == null){
try {Log.i("MyBringBack", "In run of mybringback.. getting the image of background");
backgoundImage = getAssetImage(getApplicationContext(),"backgroundhomepage");
System.gc();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ourHolder = getHolder();
while (isRunning) {
//
if (!ourHolder.getSurface().isValid()){
continue;
}
canvas = ourHolder.lockCanvas();
screenCenterX = dWidth / 2;
screenCenterY = dHeight / 2;
canvas.drawBitmap(backgoundImage, 0, 0, null);
if (imagePublishDone) {
if(!welcomeDone){
message = "Drop your wish to panda";
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
welcomeDone=true;
}
moveImageInEllipticalPath();
} else {
initialImagePublish();
}
centreReached = false;
ourHolder.unlockCanvasAndPost(canvas);
}
}
日志猫:
06-02 11:06:01.469: E/AndroidRuntime(7787): FATAL EXCEPTION: Thread-565
06-02 11:06:01.469: E/AndroidRuntime(7787): java.lang.NullPointerException
06-02 11:06:01.469: E/AndroidRuntime(7787): at android.graphics.Canvas.throwIfRecycled(Canvas.java:1037)
06-02 11:06:01.469: E/AndroidRuntime(7787): at android.graphics.Canvas.drawBitmap(Canvas.java:1078)
06-02 11:06:01.469: E/AndroidRuntime(7787): at com.example.funandlearn.DragDrop$MyBringBackSurface.run(DragDrop.java:638)
06-02 11:06:01.469: E/AndroidRuntime(7787): at java.lang.Thread.run(Thread.java:856)