0

I'm currently doing a test with a LiveWallpaper in Android. I am drawing something on the canvas using code that looks something like this:

final SurfaceHolder holder = getSurfaceHolder();
Canvas c = new Canvas();
c = holder.lockCanvas(); // c becomes null
c.save();
c.drawBitmap(currentBitmap);
c.restore();
holder.unlockCanvasAndPost(c);

This part is working fine under normal circumstances. However, I have a listener that executes this code whenever a setting is changed in the Settings that correspond to this service. It seems that whenever I execute this code from the settings activity, I am getting a NullPointer on the c.save() method.

It seems that only when the Wallpaper is not in the foreground, the holder.lockCanvas(). Is it impossible to draw to this surface when it's not in the foreground?

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
citizen conn
  • 15,300
  • 3
  • 58
  • 80

2 Answers2

2

I realize that this question is ancient, but having had the same question and having found a different answer that worked for me, I thought I'd share for posterity.

Check if SurfaceHolder.getSurface.isValid() before getting the canvas from the surface. Fixed my null canvas issues.

Blue Dev
  • 142
  • 8
2

That's right. A common way to avoid this is to unregister your listener in onPause or onVisibilityChanged(false), and reregister in onResume or onVisibilityChanged(true), since you shouldn't react to settings changes when your canvas isn't visible.

Another solution would be to simply surround that section of code with a null check, and forget about it. I'd recommend against this, though, since what you really want to do is prevent your code from even attempting to draw to the surface when it's not in view.

Josh
  • 10,618
  • 2
  • 32
  • 36
  • Yeah I could remove the listener and it would be good, the problem is I want it to redraw when the canvas isn't visible, so that when the canvas becomes visible, it will already be updated based on user settings, instead of the user seeing it change, which is what is happening now. – citizen conn Aug 05 '11 at 16:23
  • Is there something that gets called before onVisibilityChange? – citizen conn Aug 05 '11 at 16:24
  • You can call onSharedPreferencesChanged(null) when onVisibilityChanged passes `true` in to get around this. – Josh Aug 05 '11 at 16:47