• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Back camera and flash is not working.

nagamothu

Newbie
Hi can any one help me with camera.
Am trying to create custom camera with three buttons capture, switch camera , and flash .
when i capture image the image should display in Display.class and save to phone.
but when i use back camera blank page is diaplaying and when i use front camera image is displaying in display activity. Please check my code and tell me what is the problem. Logcat is not showing any error.

Custom_camera_activity.java
Code:
  @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_custom__camera );

        //Flash
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature( PackageManager.FEATURE_CAMERA_FLASH);
        if (!hasFlash) {
            // device doesn't support flash
            // Show alert message and close the application
            AlertDialog alert = new AlertDialog.Builder(Custom_CameraActivity.this)
                    .create();
            alert.setTitle("Error");
            alert.setMessage("Sorry, your device doesn't support flash light!");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // closing the application
                    finish();
                }
            });
            alert.show();
            return;
        }


        getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
        context = this;

        mCamera = Camera.open();
        mCamera.setDisplayOrientation( 90 );
        camerapreview = (LinearLayout) findViewById( R.id.camera_preview );
        mCameraPreview = new CameraPreview( context, mCamera );
        camerapreview.addView( mCameraPreview );

        capture = (ImageButton) findViewById( R.id.button_capture );
        capture.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    mCamera.takePicture( null, null, mPicture );
            }
        } );

        switchCamera = (ImageButton) findViewById(R.id.btnSwitch);
        switchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //get the number of cameras
                int camerasNumber = Camera.getNumberOfCameras();
                if (camerasNumber > 1) {
                    //release the old camera instance
                    //switch camera, from the front and the back and vice versa

                    releaseCamera();
                    chooseCamera();
                } else {


                }
            }
        });

        flash= (ImageButton)findViewById( R.id.bulb ) ;
        flash.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isFlashOn){
                    turnOffFlash();
                }else{
                    turnOnFlash();
                }
            }
        } );

        mCamera.startPreview();
        //initializeCamera();
    }

    private void turnOnFlash() {
        if (isFlashOn) {
            if (mCamera != null || params != null) {
                return;
            }
            params = mCamera.getParameters();
            params.setFlashMode( Camera.Parameters.FLASH_MODE_OFF);
            mCamera.setParameters(params);
            mCamera.stopPreview();
            isFlashOn = false;
        }
    }

    private void turnOffFlash() {

       if(!isFlashOn) {
            if (mCamera == null || params == null) {
                return;
            }
            params = mCamera.getParameters();
            ((Camera.Parameters) params).setFlashMode( Camera.Parameters.FLASH_MODE_TORCH);
           mCamera.setParameters(params);
           mCamera.startPreview();
            isFlashOn = true;

        }

    }

    private void initializeCamera() {
        int cameraId= findBackFacingCamera();
        if(cameraId >= 0){
            mCamera= Camera.open(cameraId);
            mCamera.setDisplayOrientation( 180 );
            mPicture=getPictureCallBack();
            mCameraPreview.refreshCamera( mCamera );
        }
    }


    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();

        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                cameraBack = false;
                break;
            }
        }
        return cameraId;

    }

    private int findBackFacingCamera() {
        int cameraId = -1;
        //Search for the back facing camera
        //get the number of cameras
        int numberOfCameras = Camera.getNumberOfCameras();
        //for every camera check
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                cameraId = i;
                cameraBack = true;
                break;

            }

        }
        return cameraId;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mCamera== null){
            mCamera = Camera.open();
            mCamera.setDisplayOrientation( 90 );
            mPicture= getPictureCallBack();
            mCameraPreview.refreshCamera(mCamera);
            Log.d("nu","null");
        }else{
            Log.d("nu","no null");
        }
    }

    public void chooseCamera() {
        //if the camera preview is the front
        if (cameraBack) {
            int cameraId = findFrontFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = Camera.open(cameraId);
                mCamera.setDisplayOrientation(90);
                mPicture = getPictureCallBack();
                mCameraPreview.refreshCamera(mCamera);
            }
        } else {
            int cameraId = findBackFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview
                mCamera = Camera.open(cameraId);
                mCamera.setDisplayOrientation(90);
                mPicture = getPictureCallBack();
                mCameraPreview.refreshCamera(mCamera);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    private void releaseCamera() {
        if(mCamera != null){
            mCamera.stopPreview();
            mCamera.setPreviewCallback( null );
            mCamera.release();
            mCamera= null;
        }
    }
    private Camera.PictureCallback getPictureCallBack() {
        Camera.PictureCallback picture = new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                bitmap = BitmapFactory.decodeByteArray( data,0,data.length );
                Intent intent= new Intent(Custom_CameraActivity.this,Display.class);
                startActivity( intent );
            }
        };
        return  picture;
    }

}
CameraPreview.java
Code:
public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;


    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.mCamera = camera;
        this.mHolder = this.getHolder();
        this.mHolder.addCallback(this);
        this.mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // create the surface and start camera preview
            if (mCamera == null) {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException e) {
            Log.d(VIEW_LOG_TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void refreshCamera(Camera camera){
        if(mHolder.getSurface()== null){
            return;
        }
        try{
            mCamera.stopPreview();
        }catch (Exception e){

        }
        setCamera(camera);
        try{
            mCamera.setPreviewDisplay( mHolder );
            mCamera.startPreview();
        }catch (Exception e){
            Log.d(VIEW_LOG_TAG,"Error Starting camera preview: " +e.getMessage());

        }
    }

    private void setCamera(Camera camera) {
        mCamera = camera;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder Holder, int format,
                               int width, int height) {
        // start preview with new settings
       refreshCamera( mCamera );

    }


}

Display.java
Code:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_display );

    image = findViewById( R.id.imageView );
    scancode=findViewById( R.id.scan );
    scancode.setOnClickListener( this );

    image.setImageBitmap( Custom_CameraActivity.bitmap);
    saveImage(Custom_CameraActivity.bitmap);


private String  saveImage(Bitmap mybitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(  );
    mybitmap.compress( Bitmap.CompressFormat.JPEG,90,bytes );
    File file= new File( Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
    if(!file.exists() ){
        Log.d("dirrrrrr","" + file.mkdirs());
        file.mkdirs();
    }
    try{
        File f = new File( file, Calendar.getInstance().getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream( f );
        fo.write( bytes.toByteArray() );
        MediaScannerConnection.scanFile( this,new String[]{f.getPath()} ,
                new String[]{"image/jpeg"},null);
        fo.close();
        Log.d( "TAG","File Saved:: ---- " + f.getAbsolutePath() );
        return f.getAbsolutePath();
    }catch(IOException e1){
        e1.printStackTrace();
    }
    return "";
}

Please check this code and help me to trace the issue.
 
Back
Top Bottom