Android Camera takePicture function does not call Callback function - android

I am working on a custom Camera activity for my application.
I was following the instruction from the Android Developers site here:
http://developer.android.com/guide/topics/media/camera.html
Everything seems to works fine, except the Callback function is not called and the picture is not saved. Here is my code:
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private static final String TAG = "CameraActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
// 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);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "will now take picture");
mCamera.takePicture(null, null, mPicture);
Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();
}
});
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.v(TAG, "Getting output media file");
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.v(TAG, "Error creating output file");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.v(TAG, e.getMessage());
} catch (IOException e) {
Log.v(TAG, e.getMessage());
}
}
};
private static File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File(Environment.getExternalStorageDirectory() + File.separator + "GUI");
if (!folder_gui.exists()) {
Log.v(TAG, "Creating folder: " + folder_gui.getAbsolutePath());
folder_gui.mkdirs();
}
File outFile = new File(folder_gui, "temp.jpg");
Log.v(TAG, "Returnng file: " + outFile.getAbsolutePath());
return outFile;
}
}
After clicking the Button, I get logs: "will now take picture", "will now release camera" and "will now call finish". The activity finishes succesfully, but the Callback function was not called during the
mCamera.takePicture(null, null, mPicture);
function (There were no logs from the mPicture callback or getMediaOutputFile functions) and there is no file in the location that was specified.
Any ideas? :)
Much thanks!

The call to mCamera.takePicture() is asynchronous. That means that the call completes immediately, but the actual picture taking and processing happens sometime later. However, you do this immediately upon return from the call to mCamera.takePicture():
Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();
That means that you have released the camera resources and finished the Activity before the camera gets a chance to actually take the picture and call you back.
You need to move that code into the callback method onPictureTaken() so that you release the resources and finish the Activity after the callback occurs.

Do it like this for taking multiple images on single Click Using SurfaceView Custom Camera
clickbtn.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
for (int i = 0; i < 5; i++) {
mcamera = mPreview.getCamera();
getimage(mcamera);
Toast.makeText(getApplicationContext(),
"multiple image count=" + i, 1000).show();
}
if (mPreview == null) {
mPreview = new CamLayer(MainActivity.this);
}
}
});
and
public static void getimage(Camera mcamera) {
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
Log.e("path file 11111111", ""+pictureFile);
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (Exception e) {
}
}
};
try {
mcamera.startPreview();
mcamera.takePicture(null, null, mPicture);
Thread.sleep(2000);
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Sunil3");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
File mediaFile = new File(String.format(mediaStorageDir+File.separator+"%d.jpg", System.currentTimeMillis()));
return mediaFile;
}

Related

startActivityForResult for taking photo android

I've implemented 2 methods in my application. The first, dispatchTakePictureIntent calls startActivityForResult. So when my activity it's done i get back in onActivityResult.
My applications uses events, so when i receive a particular event, i start the camera, so i can take a photo. The problem is: how can i take the photo, after i started the activity, without touching the display, and just by receiveing another event from a remote device? It's there any method i can call that take the photo instead of using fingers?
thanks
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
}
startActivityForResult(takePictureIntent, actionCode);
}
So i suppose i have to make the system call onActivityResult ..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
}
default:
break;
}
}
did It in my app, used this code:
public void takePictureNoPreview(Context context){
// open back facing camera by default
Camera myCamera=Camera.open();
if(myCamera!=null){
try{
//set camera parameters if you want to
//...
// here, the unused surface view and holder
SurfaceView dummy=new SurfaceView(context)
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.startPreview();
myCamera.takePicture(null, null, getJpegCallback()):
}finally{
myCamera.close();
}
}else{
//booo, failed!
}
private PictureCallback getJpegCallback(){
PictureCallback jpeg=new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream fos;
try {
fos = new FileOutputStream("test.jpeg");
fos.write(data);
fos.close();
} catch (IOException e) {
//do something about it
}
}
};
}
}
the code is from here I didnt modified it in my app a lot..
I implemented a custom Camera, that receives Intents through BroadcastReceiver.
The class below can be started with an intent and allows to take a photo, save it, switch cameras (Back/Front) or get back to the mainActivity by getting intents.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
View myView= (View) findViewById(R.id.camera_previeww);
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
cameraID= Camera.CameraInfo.CAMERA_FACING_FRONT;
mCamera=openCamera(cameraID);
mCamera.startPreview();
IntentFilter filter = new IntentFilter();
filter.addAction(Tabbed.BROADCAST_ACTION_TABBED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(this);
bm.registerReceiver(mBroadcastReceiver, filter);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) this.findViewById(R.id.camera_previeww);
preview.addView(mPreview);
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
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());
}
sleep(5000);
camera.startPreview();
}
};
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}else {
Log.d("MyCameraApp", "mediafile=null");
System.out.println("mediafile=null");
return null;
}
return mediaFile;
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte[] data = new byte[3];
if (intent !=null && intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
}
if (data[FINGER] == MIDDLE_FINGER && data[TYPE] == SINGLE_TAP) {
switchCamera();
//releaseCamera();
//mCamera=Camera.open();
} else if (data[FINGER] == MIDDLE_FINGER && data[TYPE] == DOUBLE_TAP) {
// HAVE TO GO BACK
onBackPressed();
//onPause();
//finish();
} else if (data[FINGER] == INDEX_FINGER && data[TYPE] == SINGLE_TAP) {
mCamera.takePicture(null, null, mPicture);
}
// kill activity
}
};
/*
#Override
public void onResume(){
super.onResume();
mCamera=openCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
}
*/
void kill_activity()
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
releaseCamera();
finish();
}
public void switchCamera(){
mCamera.stopPreview();
releaseCamera();
if (cameraID==Camera.CameraInfo.CAMERA_FACING_BACK){
cameraID=Camera.CameraInfo.CAMERA_FACING_FRONT;
}else{
cameraID=Camera.CameraInfo.CAMERA_FACING_BACK;
}
mCamera=openCamera(cameraID);
mCamera.startPreview();
CameraPreview mPreview = new CameraPreview(this, mCamera);
preview = (FrameLayout) this.findViewById(R.id.camera_previeww);
preview.removeAllViews();
preview.addView(mPreview);
}
public Camera openCamera(int cameraIDD){
Camera c=null;
try{
c=Camera.open(cameraIDD);
}catch (Exception e){
Log.d("Camera Activity", e.getMessage());
}
return c;
}
}

how can i get successive camera frame in android?

I want capture successive shooting with android camera to get HDR image using 2 image.
but my code is not working. My App is just shooting twice with no sound(no shutter sound), and no save file i have(there is no file).
First, I think that my file name was same. so, I changed my file file code like this,
// Create a media file name
// add .SSS for identity
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
Second, using synchronized and startPreview(). but still not work.
below is my capture code using "private Camera mCamera".
// Add a listener to the Capture button
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
synchronized (mPicture) {
// get an image from the camera
Camera.Parameters cp = mCamera.getParameters();
cp.setExposureCompensation(cp.getMinExposureCompensation());
mCamera.setParameters(cp);
mCamera.takePicture(null, null, mPicture);
// if i delete below 5 line then work correctly(but, just one image i can get)
mCamera.startPreview();
cp.setExposureCompensation(cp.getMaxExposureCompensation());
mCamera.setParameters(cp);
mCamera.takePicture(null, null, mPicture);
mCamera.startPreview();
}
}
}
);
and below is picture callback method.
private PictureCallback mPicture = new PictureCallback() {
String TAG = "HDR_TAG";
#Override
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());
}
}
};
Can you give me some advice?
Thanks.
(I'm sorry that my english skill is bad..)
you can get the image data continuously from camera by setting previewCallBack for camera.
camera.setPreviewCallback(previewCallback);
private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera cam) {
//get the image data here and save it..
}
};
I solved my problem using thread and endless while. See below.
#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);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
Thread t_1 = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Camera.Parameters cp = mCamera.getParameters();
cp.setAutoExposureLock(true);
mCamera.takePicture(null, null, mPicture);
}
});
Thread t_2 = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (takePicFlag != CAPTURE_SECOND)
;
Camera.Parameters cp = mCamera.getParameters();
cp.setExposureCompensation(cp
.getMinExposureCompensation());
mCamera.setParameters(cp);
mCamera.takePicture(null, null, mPicture);
}
});
Thread t_3 = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (takePicFlag != CAPTURE_THIRD)
;
Camera.Parameters cp = mCamera.getParameters();
cp.setExposureCompensation(cp
.getMaxExposureCompensation());
mCamera.setParameters(cp);
mCamera.takePicture(null, null, mPicture);
}
});
t_1.start();
t_2.start();
t_3.start();
}
});
}
and use some flag for capture.
see finally{ }.
final static String TAG = "HDR_TAG";
static int m_idenValue = 1; // 사진의 이름 중복을 방지하기위한 변수
byte[] pic_data_1;
byte[] pic_data_2;
byte[] pic_data_3;
final int CAPTURE_FIRST = 1;
final int CAPTURE_SECOND = 2;
final int CAPTURE_THIRD = 3;
int takePicFlag = CAPTURE_FIRST;
private PictureCallback mPicture = new PictureCallback() {
String TAG = "HDR_TAG";
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
// TODO Auto-generated method stub
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());
} finally {
mCamera.startPreview();
if (takePicFlag == CAPTURE_FIRST)
{
pic_data_1 = data.clone();
Log.d(TAG, "onPictureTaken, data : " + data + "\ntakePicFalg : " + takePicFlag);
takePicFlag = CAPTURE_SECOND;
}
else if(takePicFlag == CAPTURE_SECOND)
{
pic_data_2 = data.clone();
Log.d(TAG, "onPictureTaken, data : " + data + "\ntakePicFalg : " + takePicFlag);
takePicFlag = CAPTURE_THIRD;
}
else
{
pic_data_3 = data.clone();
Log.d(TAG, "onPictureTaken, data : " + data + "\ntakePicFalg : " + takePicFlag);
takePicFlag = CAPTURE_FIRST;
}
}
}
};

How send mms or sms capture photo automatically in android phone? 0

I have created my own camera application. And when I click the button it takes the picture and saves it in the galary. What I want to do is to take the picture send automatic sms or mms. Please help me how can it. My code here:
public class SimpleCameraIntentFragment extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView1);
Button captureButton = (Button) findViewById(R.id.button_capture);
System.out.println("Starting!");
// 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);
final PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
pictureFile.getAbsolutePath(),
pictureFile.getName(), pictureFile.getName());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// get an image from the camera
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
mCamera.takePicture(null, null, mPicture);
t.cancel();
//imageView.set
}
}, 5000);
}
});
}
/** 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
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private 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()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.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;
}
}
You can see some tutorial here : http://www.mkyong.com/android/how-to-send-sms-message-in-android/.
But I don't think the user appreciate a app who send automatically SMS or MMS.
The code look's like that :
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendDataMessage(....;

App crashing while building custom Camera

Application is crashing on click of the button to capture image.Kindly help.Below is my code.I have used SurfaceView to preview.I guess there is some problem with Picture CallBack
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureButton = (Button) findViewById(R.id.button_capture);
System.out.println("Starting!");
// 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);
final PictureCallback mPicture = new PictureCallback() {
#Override
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());
}
}
};
// Add a listener to the Capture button
captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// get an image from the camera
System.out.println("Photo Taking!");
mCamera.takePicture(null, null, mPicture);
}
}
);
}
/** 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
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private 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()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").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;
}
}
Logcar error:
java.lang.NullPointerException
com.example.demo.MainActivity$2.onClick(MainActivity.java:82)
android.view.View.performClick(View.java:4084)
android.view.View$PerformClick.run(View.java:16966)
android.os.Handler.handleCallback(Handler.java:615)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4745)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
dalvik.system.NativeStart.main(Native Method)

Android Camera Take Picture and SAVE or send to next activity

I’m a beginner and I need help. How do I take photos with camera and save or send to next activity?
I've tried a couple of options, i.e. takepicture with picture callback and surfaceview/take with intent. However, neither works properly on Android 2.3.3. Could someone figure out the issues with my code below?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sf_foto);
mCamera = getCameraInstance();
mCameraPreview = new SF_CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(myShutterCallback, mPicture_RAW, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(0);
camera.setDisplayOrientation(90);
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {}
};
PictureCallback mPicture_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {}
};
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent i = new Intent(StyloveFoto.this, Filter.class);
startActivity(i);
}
};
protected File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"KWAlbum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("KWAlbum", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "KW" + ".jpg");
return mediaFile;
}
my surface view:
public class SF_CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
public SF_CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
instead of this line : fos.write(data);
write : fos.write(data,0,data.length);
if you want to pass it to the next activity:
Intent i = new Intent(StyloveFoto.this, Filter.class);
i.putExtra("myImage",data);
startActivity(i);
and then in class filter in the oncreate method
byte[] myImage = getIntent()getIntent().getByteArrayExtra("myImage");
I got the same problem and i just solve it before.
The problem is that mPicture is an object of PictureCallback. You can't set intent directing to Filter.class from StyloveFoto.this, because it is in PictureCallback interface. Try this one:
Intent i = new Intent(getBaseContext() , Filter.class);
startActivity(i);
Such a big trap in java....hope it helps :)
Either you save the picture like this and pass the path to another activity
final File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + "_pic.jpg");
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OR
Pass data from camera activity :
Intent intent = new Intent(getApplicationContext(), your_class.class);
intent.putExtra("path", path);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Receiving Activity
byte[] data = getIntent().getByteArrayExtra("path");
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
image.setImageBitmap(scaleDownBitmapImage(bitmap, 300, 200));

Categories

Resources