This are my permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
This is my MainActivity.java:
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
private Camera mCamera;
private CameraPreview mPreview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
That is my activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
<Button
android:id="#+id/button_capture"
android:text="Capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
And that's my CameraPreview.java:
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("Error:", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("Error:", "Error starting camera preview: " + e.getMessage());
}
}
}
When I open the app it crashes and this Error will come:
05-16 16:17:55.694 14553-14553/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.badubadu.test, PID: 14553
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
at com.test.badubadu.test.CameraPreview.surfaceCreated(CameraPreview.java:31)
at android.view.SurfaceView.updateWindow(SurfaceView.java:622)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:161)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2205)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1250)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6311)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6217)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
EDIT Error:
05-16 22:52:39.451 18993-18993/com.test.blaba.test W/CameraBase: An error occurred while connecting to camera 0: Service not available
05-16 22:52:39.451 18993-18993/com.test.blabla.test D/Error:: Error starting camera preview: Fail to connect to camera service
05-16 22:52:39.578 18993-19091/com.test.blaba.test I/Adreno: QUALCOMM build : b6da14b, I47548ba842
Build Date : 11/14/16
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch : quic/LA.BF64.1.2.3_rb1.6
Remote Branch : NONE
Reconstruct Branch : NOTHING
So I don't know where the Error is...
Thanks for Help...:)
mCamera is null, because getCameraInstance() is returning null. Most likely, that is because Camera.open() is throwing an exception. Always make sure that you can see exceptions. During early software development, that is mostly through logging those exceptions (e.g., Log.e()).
Related
I want to call onPreviewCallback in my app but it wont start. For now there is nothing useufull on onPreviewCallback, i just want it to work. I tried to put callback in Camerapreview.java and still nothing. Can anyone tell me where i made my mistake? Here is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.nikola.camera.MainActivity">
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
MainActivity.java
package com.example.nikola.camera;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public Camera mCamera;
private CameraPreview mPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkCameraHardware(this)==false){
Toast.makeText(MainActivity.this, "This device does not have camera", Toast.LENGTH_LONG).show();
finish();
}
mCamera = getCameraInstance();
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
Log.d("Camera1","data lenght is:"+data.length);
}
});
if(mCamera==null){
Toast.makeText(MainActivity.this, "Can't access camera", Toast.LENGTH_LONG).show();
finish();
}
Camera.Parameters cameraParametars = mCamera.getParameters();
cameraParametars.setPreviewSize(640,480);
cameraParametars.setPreviewFormat(ImageFormat.RGB_565);
mCamera.setParameters(cameraParametars);
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
CameraPreview.java
package com.example.nikola.camera;
/**
* Created by Nikola on 8/4/2016.
*/
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("Camera_app", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("Camera_app", "Error starting camera preview: " + e.getMessage());
}
}
}
First permission add for camera and take image in sdcard
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On click on preview Photo is click and preview You get path in callback
preview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
Take In class Imagepath your path of image take this in your class
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Replacing the button after a photho was taken.
// File name of the image that we just took.
String fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString() + ".jpg";
// Creating the directory where to save the image. Sadly in older
// version of Android we can not get the Media catalog name
File sdRoot = Environment.getExternalStorageDirectory();
// have the object build the directory structure, if needed.
String dir = "/Capture/path/";
File mkDir = new File(sdRoot, dir);
mkDir.mkdirs();
// Main file where to save the data that we recive from the camera
File pictureFile = new File(sdRoot, dir + fileName);
String imagePath=pictureFile.getPath();
System.out.print("imagePath"+imagePath);
try {
FileOutputStream purge = new FileOutputStream(pictureFile);
purge.write(data);
purge.close();
} catch (FileNotFoundException e) {
Log.d("DG_DEBUG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
}
// Adding Exif data for the orientation. For some strange reason the
// ExifInterface class takes a string instead of a file.
try {
exif = new ExifInterface("/sdcard/" + dir + fileName);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + orientation);
exif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
}
};
But I recommended you the Camera2Basic... Which have tons of example because this is deprecated
I recommeded you to do this example which run in marashmallow or all devices work properly...
https://github.com/googlesamples/android-Camera2Basic
For face Detaction
You must register a FaceDetectionListener and then call camera.startFaceDetection().
Please see the link for face detaction..
https://docs.google.com/open?id=0B2Nu5U2Cz81qZExGQ25sWVdRd21IOExUUTZsZzFoZw
I have implemented an android camera with the help of official developer.android.com tutorial. The app is working fine sometimes but about 3/5 of times the preview of the camera freezes after some rotation and clicking the buttons or even without these works (other elements don't freeze). The cutest part is that when I debug the application the preview doesn't stuck but when I want to run the app normally sometimes the problem happens.
Here is my fullScreen Class which is consist of the codes that android studio generated for fullScreen activity and the codes for implementing surfaceHolder.Callback and camera stuff.
public class CameraActivity extends Activity implements SurfaceHolder.Callback {
... // some constants here
private Camera mCamera;
private SurfaceHolder mHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SurfaceView cameraSufaceView = (SurfaceView) findViewById(R.id.camera_preview);
// Accessing front camera to take picture
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = cameraSufaceView.getHolder();
mHolder.addCallback(this);
} else {
// Alter user
}
/**
* Gets an instance of front facing camera if available
*/
#SuppressWarnings("deprecation")
private Camera openFrontFacingCameraGingerbread() {
int cameraCount;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// start preview with new settings
try {
// mCamera.setDisplayOrientation(needs degree here);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null)
mCamera = openFrontFacingCameraGingerbread();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
When this problem happens some errors appear in the LogCat but they are not really informative. here are they:
26893-26893/com.naviiid.retinaflash E/art﹕ No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
09-16 01:34:09.336 26893-26893/com.naviiid.retinaflash E/ActivityThread﹕ appStartupEnd :
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
Caused by: java.lang.UnsatisfiedLinkError: No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
at java.lang.Runtime.appStartupEnd(Native Method)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
The only clue that I have found so far is that sometimes android calls onPause method even if the activity isn't paused. For getting instance of the camera again I call openFrontFacingCameraGingerbread() in onResume method.
Trying to create an android application to record video and capture images. I've followed the tutorials thus far with some success however I must have a lack of knowledge about the android sdk to not be able to get around this issue. No doubt I will feel stupid once someone figures this out but I'm here to learn in the end.
Here is the MainActivity.java
package example.myapplication;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
public MainActivity(Context context) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/** Check if this device has a camera */
public boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the CameraPreview.java
package example.myapplication;
import android.content.Context;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/** A basic Camera preview class */
public class CameraPreview extends MainActivity implements SurfaceHolder.Callback {
private android.hardware.Camera.PictureCallback mPicture;
private Camera mCamera;
private CameraPreview mPreview;
private SurfaceHolder mHolder;
private SurfaceHolder holder;
public void setContentView(int activity_camera) {}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final String TAG = "CameraPreview";
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onClick() {
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0){
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
});
}
public SurfaceHolder getHolder() {
return holder;
}
public void setHolder(SurfaceHolder holder) {
this.holder = holder;
}
}
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera2" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and the logcat
Process: example.myapplication, PID: 20671
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{example.myapplication/example.myapplication.MainActivity}: java.lang.InstantiationException: can't instantiate class example.myapplication.MainActivity; no empty constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: can't instantiate class installation04.myapplication.MainActivity; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
A couple of things that need to be sorted:
Please remove all constructors from classes that extend Activity. - Activities do not work this way. Please look read how Activity Life cycle works.
Please add the CameraPreview activity to your manifest as well.
delete MainActivity constructor
public MainActivity(Context context) {
}
Please read carefully the stacktrace:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{example.myapplication/example.myapplication.MainActivity}:
java.lang.InstantiationException: can't instantiate class
example.myapplication.MainActivity; no empty constructor
You have created constructor in your Activity. Remove the constructor from your Activities and use the Lifecycle callbacks.
As per android guidelines you should not create constructor in the Activity classes since android OS creates object of Activity classes and it use the default empty constructor of the class to create object.
im trying to run a Camera Service in the Background, as soon after the Service has started i get an error takePicture failed. I'm new to Android,new to Stackoverflow and also not a good programmer.
I've added the right permissions and the service has been declared in the manifest file too.
package com.example.nevii.camera;
import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
public class CameraService extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
private boolean safeToTakePicture = false;
/** Called when the activity is first created. */
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
Toast.makeText(getBaseContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
mCamera = Camera.open(1);
mCamera.setDisplayOrientation(90);
SurfaceView sv = new SurfaceView(getApplicationContext());
try {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
safeToTakePicture = true;
takePic();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return START_STICKY;
}
public void takePic(){
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//decode the data obtained by the camera into a Bitmap
MyCamera myCamera = new MyCamera();
myCamera.SavePicture(data);
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
};
mCamera.takePicture(null, null, mCall);
Toast.makeText(getApplicationContext(),"Pic taken",Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I got the SourceCode from here:http://androideasylessons.blogspot.ch/2012/09/capture-image-without-surface-view-as.html
In the MainActivity i started the Service using:
startService(new Intent(this, CameraService.class));
myCamera.SavePicture is just an Asynchtask, which saves the Picture, i don't think there's a problem with that.
I hope you guys can help me.
Happy Coding!
UPDATE Logcat Error:
03-03 09:04:46.150 27530-27530/com.example.nevii.videocam D/Camera﹕ app passed NULL surface
03-03 09:04:46.153 27530-27530/com.example.nevii.videocam D/AndroidRuntime﹕ Shutting down VM
03-03 09:04:46.154 27530-27530/com.example.nevii.videocam E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nevii.videocam, PID: 27530
java.lang.RuntimeException: Unable to start service com.example.nevii.videocam.CameraService#3f53f37f with Intent { cmp=com.example.nevii.videocam/.CameraService }: java.lang.RuntimeException: takePicture failed
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2881)
at android.app.ActivityThread.access$2100(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1436)
at android.hardware.Camera.takePicture(Camera.java:1381)
at com.example.nevii.videocam.CameraService.takePic(CameraService.java:101)
at com.example.nevii.videocam.CameraService.onStartCommand(CameraService.java:57)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2864)
at android.app.ActivityThread.access$2100(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
just add SurfaceTexture st = new SurfaceTexture(MODE_PRIVATE); mCamera.setPreviewTexture(st);
before mCamera.startPreview();
Pretty new on this android stuff and gets a NullPointException that I can't seem to figure out. I am trying to implement an onResume() method in my CameraActivity and have moved almost all of the orginal code in onCreate() to onResume() and then call onResume() in onCreate(). The activity worked fine when the code was in onCreate(), but when placed in onResume() the exception arsises. What is causing it?
package com.example.tensioncamapp_project;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PreviewAactivity";
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
this.mHolder = getHolder();
this.mHolder.addCallback(this);
}
/**Displays the picture on the camera */
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
this.mCamera.setPreviewDisplay(holder);
this.mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
this.mCamera.release();
this.mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
//add things here
}
}
and my CameraActivityClass
package com.example.tensioncamapp_project;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.content.Intent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private ImageButton captureButton;
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private ImageView imageView;
private static final int STD_DELAY = 400;
private static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "CameraActivity";
/**Starts up the camera */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
onResume();
}
/**Connects the capture button on the view to a listener
* and redirects the client to a preview of the captures image*/
private void addListenerOnButton() {
this.captureButton = (ImageButton) findViewById(R.id.button_capture_symbol);
this.captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View capturebutton) {
mCamera.takePicture(null, null, mPicture);
delay();
Intent viewPic = new Intent(CameraActivity.this, ViewPicActivity.class);
startActivity(viewPic);
}
});
}
/** A safe way to get an instance of the Camera object. Code collected from elsewhere */
public static Camera getCameraInstance(){
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
//getting current parameters
Camera.Parameters params = c.getParameters();
//setting new parameters with flash
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
c.setParameters(params);
}
catch (Exception e){
// camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
/**Generates a delay needed for application to save new pictures */
private void delay(){
try {
//Makes the program inactive for a specific amout of time
Thread.sleep(STD_DELAY);
} catch (Exception e) {
e.getStackTrace();
}
}
/**Method for releasing the camera immediately on pause event*/
#Override
protected void onPause() {
super.onPause();
//Shuts down the preview shown on the screen
mCamera.stopPreview();
//Calls an internal help method to restore the camera
releaseCamera();
}
/**Help method to release the camera */
private void releaseCamera(){
//Checks if there is a camera object active
if (this.mCamera != null){
//Releases the camera
this.mCamera.release();
//Restore the camera object to its initial state
this.mCamera = null;
}
}
/**Activates the camera and makes it appear on the screen */
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
this.mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
this.mPreview = new CameraPreview(this, this.mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(this.mPreview);
//add the capture button
addListenerOnButton();
// In order to receive data in JPEG format
this.mPicture = new PictureCallback() {
/**Creates a file when a image is taken, if the file doesn't already exists*/
#Override
public void onPictureTaken(byte[] data, Camera mCamera) {
File pictureFile = FileHandler.getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
//Writes the image to the disc
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
super.onResume();
}
}
Log cat:
05-21 14:32:05.424: D/OpenGLRenderer(1030): Enabling debug mode 0
05-21 14:32:10.986: E/CameraActivity(1030): camera not availableFail to connect to camera service
05-21 14:32:11.033: I/Choreographer(1030): Skipped 66 frames! The application may be doing too much work on its main thread.
05-21 14:32:11.203: W/EGL_emulation(1030): eglSurfaceAttrib not implemented
05-21 14:32:13.013: D/AndroidRuntime(1030): Shutting down VM
05-21 14:32:13.013: W/dalvikvm(1030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-21 14:32:13.083: E/AndroidRuntime(1030): FATAL EXCEPTION: main
05-21 14:32:13.083: E/AndroidRuntime(1030): java.lang.NullPointerException
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.example.tensioncamapp_project.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doFrame(Choreographer.java:532)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.handleCallback(Handler.java:725)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Looper.loop(Looper.java:137)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invoke(Method.java:511)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-21 14:32:13.083: E/AndroidRuntime(1030): at dalvik.system.NativeStart.main(Native Method)
The solution was to call the getCameraInstancemethod() in onResume() in an if-statement
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
if (this.mCamera == null){
this.mCamera = getCameraInstance();}
I think your problem is here
this.mPreview = new CameraPreview(this, this.mCamera);
this.mCamera seems to be null, it's not be set a new instance of the class, this needs to be done in the getCameraInstance() method.
getCameraInstance() returns null if an exception was thrown.
This cause the NPE as this.mCamera is null.
You should check if an exception was thrown in getCameraInstance and handle it correctly. The most basic thing is to log it and try to understand the reason.