简体   繁体   中英

Getting a null pointer exception while trying to draw on canvas textureview android?

I am trying to drawn on a TextureView with a canvas in Android. I am doing it inside a thread but for some reason, when I try to run my program, I am getting a null pointer exception . I have implemented my thread in the surfaceAvailable() callback but I'm still unable to draw. What could I be doing wrong?

This is what i tried so far:

This is my stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int, android.graphics.PorterDuff$Mode)' on a null object reference

I believe the problem is here:

final Canvas canvas = mSurface.lockCanvas(null);

Take a look at the official documentation:

lockCanvas

public abstract Canvas lockCanvas ()

Start editing the pixels in the surface. The returned Canvas can be used to draw into the surface's bitmap. .You will usually need to implement Callback.surfaceCreated to find out when the Surface is available for use.

You might be trying to draw on a surface before it has been created. In this case, you must make sure that lockCanvas() is only called after the surface is ready (listen for the surface creation). Also, in your case, you should use the lockCanvas() without arguments, like this:

final Canvas canvas = mSurface.lockCanvas();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM