-2

I am creating an app in which I'm using front camera.Please tell me how to open front camera when click on button using following code.My app is crashed when i click on button to open the camera.

public class MakePhotoActivity extends Activity {

// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();


// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

private Uri fileUri; // file url to store image/video

private Button btnCapturePicture, btnRecordVideo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_make_photo);

    // Changing action bar background color
    // These two lines are not needed
   // getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
    btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

    /**
     * Capture image button click event
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

    /**
     * Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });

    // Checking camera availability
    if (!isDeviceSupportCamera()) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device does't have camera
        finish();
    }
}

/**
 * Checking device has camera hardware or not
 * */
private boolean isDeviceSupportCamera() {
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

/**
 * Launching camera app to capture image
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    //intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);


}

/**
 * Launching camera app to record video
 */
private void recordVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
    // name

    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}



/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            // successfully captured the image
            // launching upload activity
            launchUploadActivity(true);


        } else if (resultCode == RESULT_CANCELED) {

            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            // video successfully recorded
            // launching upload activity
            launchUploadActivity(false);

        } else if (resultCode == RESULT_CANCELED) {

            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

private void launchUploadActivity(boolean isImage){
   /* Intent i = new Intent(MakePhotoActivity.this, UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);
    startActivity(i);*/
}

/**
 * ------------ Helper Methods ----------------------
 * */

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {

    return Uri.fromFile(getOutputMediaFile(type));
}


/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create " + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    }  else {

        return null;
    }

    return mediaFile;
}
}

when i click on button to open the camera app is crashed. i am get this error

07-12 14:02:50.028 15360-15360/com.camerimageuploadd E/AndroidRuntime: FATAL >EXCEPTION: main

Process: com.camerimageuploadd, PID: 15360 java.lang.NullPointerException: file at android.net.Uri.fromFile(Uri.java:453) at com.camerimageuploadd.MakePhotoActivity.getOutputMediaFileUri(MakePhotoActivity.java:228) at com.camerimageuploadd.MakePhotoActivity.captureImage(MakePhotoActivity.java:110) at com.camerimageuploadd.MakePhotoActivity.access$000(MakePhotoActivity.java:27) at com.camerimageuploadd.MakePhotoActivity$1.onClick(MakePhotoActivity.java:64) at android.view.View.performClick(View.java:6294) at android.view.View$PerformClick.run(View.java:24770) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Please help how can i resolved this.

Thanks

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
Alisha Sharma
  • 39
  • 2
  • 8

1 Answers1

0

its throwing null ponter exception because your code is trying to acces file which is not yet captured by camera

 fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

and

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

i suggest to use this both lines in onActivityResult

your updated methods is

private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);      
    }

and

 private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }

Your OnActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                Toast.makeText(getApplicationContext(),""+fileUri,Toast.LENGTH_LONG).show();
//                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                // successfully captured the image
                // launching upload activity
                launchUploadActivity(true);


            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }

        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                Toast.makeText(getApplicationContext(),""+fileUri,Toast.LENGTH_LONG).show();
                // video successfully recorded
                // launching upload activity
                launchUploadActivity(false);

            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
Vinesh Chauhan
  • 1,288
  • 11
  • 27
  • not working again crash when i put these lines in onActivityResult – Alisha Sharma Jul 12 '18 at 09:12
  • i am getting this error now.....FATAL EXCEPTION: main Process: com.camerimageuploadd, PID: 19359 java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.activity.CaptureActivity (has extras) } from ProcessRecord{a6a08de 19359:com.camerimageuploadd/u0a124} (pid=19359, uid=10124) with revoked permission android.permission.CAMERA – Alisha Sharma Jul 12 '18 at 09:18
  • These permission are using .... – Alisha Sharma Jul 12 '18 at 09:19
  • not allowed in setting check it again in settings> Apps> Your App Name – Vinesh Chauhan Jul 12 '18 at 09:19
  • @ Alisha Sharma you have to add runtime permissions to access camera and external storage if you are using sdk version >=23. – Bhagyashri Jul 12 '18 at 09:22
  • @userl you are right but for testing pupose you can allow from setting – Vinesh Chauhan Jul 12 '18 at 09:24
  • okk.. i will do this...but one more issue when i captured image then i click on save button Camera App is stopped. – Alisha Sharma Jul 12 '18 at 09:25
  • camera is open and capture image both are working fine.. but after click right tick to process image Camera App is stopped – Alisha Sharma Jul 12 '18 at 09:32
  • E/AndroidRuntime: FATAL EXCEPTION: main Process: com.google.android.GoogleCamera, PID: 22365 java.lang.NullPointerException at iya.b(PG:39) at jht.b(PG:1) at cys.e(PG:10) at cys.b(PG:52) at ni.b(PG:13) at cni.a(PG:38) at cut.a(PG:9) at gud.a(PG:17) at com.google.android.apps.camera.shutterbutton.ShutterButton.performClick(PG:160) at android.view.View$PerformClick.run(View.java:24770) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) – Alisha Sharma Jul 12 '18 at 09:40
  • mail sent..please check – Alisha Sharma Jul 12 '18 at 09:54
  • please mail source files – Alisha Sharma Jul 12 '18 at 10:03