0

I have implemented custom Android SurfaceView and meet error when I add callback for it.

Here is my code for class SurfaceView:

public class AndroidSurface extends SurfaceView {

    public SurfaceHolder holder;

    public AndroidSurface(Context context, AttributeSet attrs) {
        super(context, attrs);

        holder = getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {

            public void surfaceChanged(SurfaceHolder holder, int format,
                    int width, int height) {
                // TODO Auto-generated method stub

            }

            public void surfaceCreated(SurfaceHolder holder) {
                // TODO Auto-generated method stub

            }

            public void surfaceDestroyed(SurfaceHolder holder) {
                // TODO Auto-generated method stub

            }


        });
    }
}

When I add this view to layout.xml, for example :

<com.app.AndroidSurface
        android:id="@+id/surfaceView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/rightBtn"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1" />

I will met error when show in Graphical Layout : failed to instantiate. (at Plugin : com.android.ide.eclipse.adt) and when run this project, I will have exception. When view in LogCat, I see that Java Null Point Exception.

The strange thing is : if I remove holder.addCallback(new SurfaceHolder.Callback() {... no error met.

This looks strange too me, please tell me how to fixed this.

@ Edited : and the problem because when I getHolder, it doesn't return surface holder, so holder is null, I don't know why.

Thanks :)

hqt
  • 29,632
  • 51
  • 171
  • 250
  • Post the logcat. Check if the holder is null. Click on the line where you package name is shown in red. This will take to exactl stop. – Code Droid Aug 06 '12 at 18:04
  • 1
    You can also debug and set a breakpoint on the holder to see if it is null. – Code Droid Aug 06 '12 at 18:05
  • 1
    post getHolder() please. It might not be working correctly. – Code Droid Aug 06 '12 at 18:05
  • @CodeDroid oh, yes, you right, `holder`is null, and I don't think this before. But, why it is null, please help me. Thanks :) – hqt Aug 06 '12 at 18:11
  • If you wrote it, you should know what is returning null or how its null. – JoxTraex Aug 06 '12 at 18:19
  • Oh. I have a silly mistake, when I create this class, I have created a getter with this which name is : `getHolder`, that why my program went wrong !!! – hqt Aug 06 '12 at 18:25

1 Answers1

0

You should check your context and make sure you are doing things in the correct order with respect to your lifecycle. Check out this post surfaceView.getHolder not returning SurfaceHolder

Community
  • 1
  • 1
Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64