大家看一下这段代码问题出在什么地方
public Bitmap process(Bitmap curSingerBmp) { System.gc(); if (mBack != null && !mBack.isRecycled()) { mBack.recycle(); mBack = null; } try { mBack = Bitmap.createBitmap(mPhotoFrame.getWidth(),mPhotoFrame.getHeight(), Bitmap.Config.ARGB_8888); } catch(Exception e) { e.printStackTrace(); }mSingerImage = curSingerBmp; Canvas cv = new Canvas(mBack); Paint p = new Paint(); mLeftLength = (mBack.getWidth() - mSingerImage.getWidth()) / 2; mTopLenght = (mBack.getHeight() - mSingerImage.getHeight()) / 2; cv.drawBitmap(mPhotoFrame,0,0, p); cv.drawBitmap(mSingerImage,mLeftLength,mTopLenght, p); cv.drawBitmap(mPhotoFrame_Front,0,0, p); mSingerImage.recycle(); mSingerImage = null; return mBack; }乍一看好像也没有什么问题,你看该捕捉的异常也捕捉了。
但是各位看官,问题就是出现在这个异常捕捉上面。
大家仔细的看下面
try { mBack = Bitmap.createBitmap(mPhotoFrame.getWidth(),mPhotoFrame.getHeight(), Bitmap.Config.ARGB_8888); } catch(Exception e) { e.printStackTrace(); }mSingerImage = curSingerBmp; Canvas cv = new Canvas(mBack);
虽然在创建一个Bitmap对象mBack的时候是捕捉了异常,但是代码却依然执行,这样就会导致当mBack创建失败。
但是依然执行
Canvas cv = new Canvas(mBack);结果就会报一个空指针的异常
所以上面的代码需要做如下的修改
try { mBack = Bitmap.createBitmap(mPhotoFrame.getWidth(),mPhotoFrame.getHeight(), Bitmap.Config.ARGB_8888);mSingerImage = curSingerBmp; Canvas cv = new Canvas(mBack);} catch(Exception e) {e.printStackTrace();}
也就是说当程序出现了异常时候,就不要让程序继续执行正确的业务逻辑了,不然,不仅前面的异常白捕捉了,还会给我们的应用程序带来更严重的问题。