[Java for Android App Development] shweta123:
I am making an android app which requires to capture image using front camera using android service. Also we need to detect face in the image so obtained. But when calling the detectfaces() function, the app unfortuantely stops. I am posting the code for it here. Please help me find out where i am going wrong.

here is my code..!!!!

package com.android.camerarecorder;

import android.app.Activity;

import android.content.Intent;

import android.hardware.Camera;

import android.os.Bundle;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.TextView;

public class CameraRecorder extends Activity implements SurfaceHolder.Callback {

static final int MAX_FACES = 5;

//private static final String TAG = "Recorder";

public static SurfaceView mSurfaceView;

public static SurfaceHolder mSurfaceHolder;

public static Camera mCamera;

public static boolean mPreviewRunning;

public static TextView jpgName;

public static ImageView jpgView;

public static ImageView imageView;

/** Called when the activity is first created. */

[MENTION=5448622]Suppress[/MENTION]Warnings("deprecation")
[MENTION=439709]override[/MENTION]

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

imageView = (ImageView)findViewById(R.id.jpgview);

mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);

jpgName = (TextView)findViewById(R.id.jpgname);

jpgView = (ImageView)findViewById(R.id.jpgview);

mSurfaceHolder = mSurfaceView.getHolder();

mSurfaceHolder.addCallback(this);

mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

Button btnStart = (Button) findViewById(R.id.StartService);

btnStart.setOnClickListener(new View.OnClickListener()

{

public void onClick(View v)

{

Intent intent = new Intent(CameraRecorder.this,RecorderService.class);

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startService(intent);

//finish();

}

});

Button btnStop = (Button) findViewById(R.id.StopService);

btnStop.setOnClickListener(new View.OnClickListener()

{

public void onClick(View v)

{

stopService(new Intent(CameraRecorder.this, RecorderService.class));

}

});

}

[MENTION=439709]override[/MENTION]

public void surfaceCreated(SurfaceHolder holder) {

}

[MENTION=439709]override[/MENTION]

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

[MENTION=439709]override[/MENTION]

public void surfaceDestroyed(SurfaceHolder holder) {

// TODO Auto-generated method stub

}

}

The above code was the activity where the service is called. The service is as follows:

package com.android.camerarecorder;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import android.app.Service;

import android.content.ContentValues;

import android.content.Context;

import android.content.CursorLoader;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.PointF;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.Bitmap.Config;

import android.hardware.Camera;

import android.hardware.Camera.CameraInfo;

import android.hardware.Camera.Parameters;

import android.media.AudioManager;

import android.media.FaceDetector;

import android.media.FaceDetector.Face;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.os.IBinder;

import android.provider.MediaStore;

import android.provider.MediaStore.Images.Media;

import android.util.Log;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

public class RecorderService extends Service

{

private SurfaceHolder sHolder;

private TextView mjpgname;

private ImageView mjpgview;

private ImageView mimageview;

Bitmap bm;

Bundle bundle = new Bundle();

String filename;

private int cameraId = 0;

//a variable to control the camera

private Camera mCamera;

final static String DEBUG_TAG = "Test";

Uri imageFileUri;

//the camera parameters

private Parameters parameters;

/** Called when the activity is first created. */

[MENTION=439709]override[/MENTION]

public void onCreate()

{

super.onCreate();

sHolder=CameraRecorder.mSurfaceHolder;

mCamera = CameraRecorder.mCamera;

mjpgname= CameraRecorder.jpgName;

mjpgview = CameraRecorder.jpgView;

mimageview=CameraRecorder.imageView;

}

[MENTION=5448622]Suppress[/MENTION]Warnings("deprecation")
[MENTION=439709]override[/MENTION]

public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

super.onStart(intent, startId);

// do we have a camera?

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();

} else {

cameraId = findFrontFacingCamera();

if (cameraId < 0) {

Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();

} else {

mCamera = Camera.open(cameraId);

}

}

//mCamera = Camera.open();

SurfaceView sv = new SurfaceView(getApplicationContext());

sv=CameraRecorder.mSurfaceView ;

try {

mCamera.setPreviewDisplay(sHolder);

parameters = mCamera.getParameters();

//set camera parameters

mCamera.setParameters(parameters);

mCamera.startPreview();

mCamera.takePicture(null, null, mCall);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

//Get a surface

sHolder = sv.getHolder();

//tells Android that this surface will have its data constantly replaced

sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

}

private int findFrontFacingCamera() {

int cameraId = -1;

// Search for the front facing camera

int numberOfCameras = Camera.getNumberOfCameras();

for (int i = 0; i < numberOfCameras; i++) {

CameraInfo info = new CameraInfo();

Camera.getCameraInfo(i, info);

if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {

Log.d(DEBUG_TAG, "Camera found");

cameraId = i;

break;

}

}

return cameraId;

// TODO Auto-generated method stub

}

Camera.PictureCallback mCall = new Camera.PictureCallback()

{

public void onPictureTaken(byte[] data, Camera camera)

{

//decode the data obtained by the camera into a Bitmap

// FileOutputStream outStream = null;

try{

imageFileUri = getContentResolver().insert(

Media.EXTERNAL_CONTENT_URI, new ContentValues());

OutputStream imageFileOS = getContentResolver().openOutputStream(

imageFileUri);

imageFileOS.write(data);

imageFileOS.flush();

imageFileOS.close();

filename = getRealPathFromURI(imageFileUri);

File imgFile = new File(filename);

if(imgFile.exists())

{

bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

mjpgview.setImageBitmap(bm);

}

detectFaces();

// mjpgname.setText("success");

/*

Intent i = new Intent(RecorderService.this, FaceDetect.class);

//Add your data to bundle

bundle.putString("Filepath", filename) ;

//Add the bundle to the intent

i.putExtras(bundle);

//Fire that second activity

startActivity(i);*/

/* final File images = Environment.getExternalStorageDirectory();

String filePath = "magic";

String final_path = images+"/"+filePath;

outStream = new FileOutputStream(final_path);

outStream.write(data);

outStream.close();*/

} catch (FileNotFoundException e){

Log.d("CAMERA", e.getMessage());

} catch (IOException e){

Log.d("CAMERA", e.getMessage());

}

}

};

private void detectFaces() {

if(null != bm){

int width = bm.getWidth();

int height = bm.getHeight();

FaceDetector detector = new FaceDetector(width, height,CameraRecorder.MAX_FACES);

Face[] faces = new Face[CameraRecorder.MAX_FACES];

Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);

Paint ditherPaint = new Paint();

Paint drawPaint = new Paint();

ditherPaint.setDither(true);

drawPaint.setColor(Color.RED);

drawPaint.setStyle(Paint.Style.STROKE);

drawPaint.setStrokeWidth(2);

Canvas canvas = new Canvas();

canvas.setBitmap(bitmap565);

//canvas.setBitmap(cameraBitmap);

canvas.drawBitmap(bm, 0, 0, ditherPaint);

int facesFound = detector.findFaces(bitmap565, faces);

// int facesFound = detector.findFaces(cameraBitmap, faces);

PointF midPoint = new PointF();

float eyeDistance = 0.0f;

float confidence = 0.0f;

Log.i("FaceDetector", "Number of faces found: " + facesFound);

if(facesFound > 0)

{

for(int index=0; index<facesFound; ++index){

faces[index].getMidPoint(midPoint);

eyeDistance = faces[index].eyesDistance();

confidence = faces[index].confidence();

Log.i("FaceDetector",

"Confidence: " + confidence +

", Eye distance: " + eyeDistance +

", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");

canvas.drawRect((int)midPoint.x - eyeDistance ,

(int)midPoint.y - eyeDistance ,

(int)midPoint.x + eyeDistance,

(int)midPoint.y + eyeDistance, drawPaint);

}

}

// Camera_timer.key = eyeDistance;

// tv.setText(eyeDistance+"");

String filepath = Environment.getExternalStorageDirectory()

+ "/facedetect" +System.currentTimeMillis() + ".jpg";

try {

FileOutputStream fos = new FileOutputStream(filepath);

bitmap565.compress(CompressFormat.JPEG, 90, fos);

// cameraBitmap.compress(CompressFormat.JPEG, 90, fos);

fos.flush();

fos.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

mimageview.setImageBitmap(bitmap565);

// imageView.setImageBitmap(cameraBitmap);

}

}

private String getRealPathFromURI(Uri contentUri) {

String[] proj = { MediaStore.Images.Media.DATA };

//This method was deprecated in API level 11

//Cursor cursor = managedQuery(contentUri, proj, null, null, null);

CursorLoader cursorLoader = new CursorLoader((Context) mCall,contentUri, proj, null, null,null);

Cursor cursor = cursorLoader.loadInBackground();

int column_index =

cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

cursor.moveToFirst();

return cursor.getString(column_index);

// TODO Auto-generated method stub

}

[MENTION=439709]override[/MENTION]

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}

}