Reputation: 173
I have a class that extends View. This class has the member variable mCanvas
private Canvas mCanvas;
This variable is created when the view is resized, so the appropriate sizes for the canvas are set:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= w && curH >= h) {
return;
}
if (curW < w) curW = w;
if (curH < h) curH = h;
Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(canvasBitmap);
if (mBitmap != null) {
mCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = canvasBitmap;
}
But in my onDraw function i'm getting a null pointer exception when i try get the width/height of my canvas. I was unsure when onSizeChanged is actually getting called, i was assuming it would always get called when the view was created and therefore before onDraw.
But if my onDraw starts with this:
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
Log.d("testing","mCanvas is null"
}
logCat always shows the message "mCanvas is null" when i reach onDraw.
So i changed the code so that if mCanvas is null when i read onDraw i just create it again:
private void resizeCanvas()
{
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= this.getWidth() && curH >= this.getHeight()) {
return;
}
if (curW < this.getWidth()) curW = this.getWidth();
if (curH < this.getHeight()) curH = this.getHeight();
Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(canvasBitmap);
if (mBitmap != null) {
mCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = canvasBitmap;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
resizeCanvas();
if(mCanvas == null)
{
Log.d("test","canvas is still null");
}
logCat still prints "canvas is still null"
Can someone explain what is happening here? I'm very new with android and most of this code is from the touchpaint example that i've been playing with.
If i check inside the resizeCanvas function if mCanvas is null it always says it is not null. But if i check just after calling that function it is always null.
Upvotes: 3
Views: 297
Reputation: 745
I think the problem is in your resizeCanvas
as you can return from it before initializing mCanvas
.
Upvotes: 4