androidsurfaceholder

holder.getSurface().isValid() is returning false


I am using Surfaceview to change the background image. But I am getting false on holder.getSurface().isValid() and I don't know why. I looked at some of the similar questions here, but still could not solve it. Is there something missing on what I have done so far, or is there something else I should try

Thanks

import android.content.Context;

import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class BrickSmasherView extends SurfaceView {



    SurfaceHolder holder;




    Canvas canvas;
    Context context;

    Thread back = null;

    volatile boolean running = false;

    public BrickSmasherView(Context context) {
        super(context);
        this.context = context;
        holder = getHolder();

    }
    public void runbackThread(){
        back = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    draw();
                }
            }
        });
        back.start();
    }




    public  void resumegame(){
        running = true;
       runbackThread();

    }

    public void pausegame(){

        running = false;
        try
        {
            back.join();


        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public void  draw(){
    if(holder.getSurface().isValid()){
        canvas = holder.lockCanvas();
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.sky),0,0,null);
        holder.unlockCanvasAndPost(canvas);
    }
}

}

Solution

  • You had to add Callback in the SurfaceView to receive events about Surface availability and do drawing from a thread.

    A Callback Example will look like this :

    public class MyCallback implements SurfaceHolder.Callback {
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, 
            int width, int height) {    
        }
    
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // you need to start your drawing thread here
        }
    
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {  
            // and here you need to stop it
        }
    }
    

    And than you need to set this callback to SurfaceHolder:

    surface.getHolder().addCallback(new MyCallback());
    

    Try this please. I Think It will help you