How to Program the Google Android Camera to Take Pictures

Written by:  • Edited by: Simon Hill
Updated May 31, 2011
• Related Guides: Android

Learn how to program the Google Android camera to take pictures in the simplest way via the Google Android Programming Environment.

Introduction

Nowadays smartphones have a great number of hardware enhancements: camera, accelerometer, GPS, Wi-Fi... It's time to start using their whole functionality on our phones. Let's learn how to use the phone's camera. In this example, we will need to work with 2 files, the layout file and the activity file.

Hint! → Some time ago, there was a software actualization for the 1.5 (cupcake) Android phones. It was a security improvement. One of these security changes was related to camera permission. Before this actualization, you were able to create applications that take pictures without the user's permission. Now, this issue is fixed, and if you want to use the camera in your application, you need to add the corresponding line in the AndroidManifest.xml. The line is as follows:

<uses-permission android:name="android.permission.CAMERA"/>

(More about the AndroidManifest.xml in the article How to understand the AndroidManifest.xml file in your Android Programming Environment)

Camera Layout

This is the easiest element to develop, well, it depends on how many improvements we want to add into our application, elements, buttons with camera functionality...we are going to do it in the simplest way. No buttons, no extra camera functionality, just take pictures. Let's have a look at the layout we are going to use.

We can call it “camera_surface.xml

Hint!-> Remember! You cannot use capital letters in the resources elements, if you put “CameraSurface.xml” it will give you problems.

Here it is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent" android:layout_height="fill_parent"

android:orientation="vertical">

<SurfaceView android:id="@+id/surface_camera"

android:layout_width="fill_parent" android:layout_height="10dip"

android:layout_weight="1">

</SurfaceView>

</LinearLayout>

Very simple, eh? Just a LinearLayout (our container) and inside of it, a SurfaceView. SurfaceViews provides us a dedicated place to draw things on it, in this case, our camera screen.

Camera Implementation code

Now we have to take a look at the xml code for our camera, let's have a look at the Android code. Let's create an activity called “CameraView” that implements the interface SurfaceHolder.Callback.

public class CamaraView extends Activity implements SurfaceHolder.Callback

This interface “SurfaceHolder.Callback” is used to receive information about changes that occur in the surface (in this case, the camera preview). SurfaceHolder.Callback implements three methods:

surfaceChanged

This method is called when the size or the format of the surface changes.

surfaceCreated

When, in the first instance, the surface is created, this method is called.

surfaceDestroyed

This is called when the surface is destroyed.

Camera Code Continued

Let's have a look at how to use this interface in our camera application. We'll use the onCreate method in our activity.

super.onCreate(icicle);

getWindow().setFormat(PixelFormat.TRANSLUCENT);

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.camera_surface);

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

mSurfaceHolder = mSurfaceView.getHolder();

mSurfaceHolder.addCallback(this);

mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

}

Let's comment the code lines.

getWindow().setFormat(PixelFormat.TRANSLUCENT);

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

With these lines, we are telling the screen that:

-The camera preview is going to be full-screen, without “title” (No notification bar).

-The format of the screen allows “translucency”.

setContentView(R.layout.camera_surface );

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

We set the layout to the Activity with the setContentView to the camera_surface (the one we created some lines above!) and we create a SurfaceView object, getting it from the xml file.

mSurfaceHolder = mSurfaceView.getHolder();

mSurfaceHolder.addCallback(this);

mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

With these lines, we get the holder from the surfaceview, and we add the callback function to “this”. This means that our activity is going to manage the surfaceview.

Let's see how the callback functions are implemented.

public void surfaceCreated(SurfaceHolder holder) {

mCamera = Camera.open();

mCamera is an Object of the class “Camera”. In the surfaceCreated we “open” the camera. This is how to start it!!

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

if (mPreviewRunning) {

mCamera.stopPreview();

}

Camera.Parameters p = mCamera.getParameters();

p.setPreviewSize(w, h);

mCamera.setParameters(p);

try {

mCamera.setPreviewDisplay(holder);

} catch (IOException e) {

e.printStackTrace();

}

mCamera.startPreview();

mPreviewRunning = true;

}

This is the method that prepares the camera, sets parameters and starts the preview of the image in our Android screen. I have used a “semaphore” parameter to prevent crashing: when the mPreviewRunning is true, it means that the camera is active and has not “closed”, so this way we can work with it.

public void surfaceDestroyed(SurfaceHolder holder) {

mCamera.stopPreview();

mPreviewRunning = false;

mCamera.release();

}

This is the method where we stop the camera and release the resources associated to the camera. See, that here we set the mPreviewRunning flat to “false”, with this, we prevent crashing in the surfaceChanged method. Why? Because this means that we have “closed” the camera, and we cannot set parameters or start image previews in our camera (stuff that the surfaceChanged method does) if it is closed!.

And let's finish with the most important method:

Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

public void onPictureTaken(byte[] imageData, Camera c) {

}

};

This method is called when a picture is taken. For example, you could create an OnClickListener on the screen that calls the PictureCallBack method when you click on the screen. This method just gives you the byte[] of the image. So, just convert it from byte[] to some image format you want, using the Bitmap and BitmapFactory class that Android offers us. This will be explained in another tutorial!!

Conclusion

I hope this was helpful for everyone. It should be pretty clear if you have a basic grasp of Android programming. However, maybe some concepts like “Callback”, “interface” or “listener” are not clear yet. I will write a post about these “generic” words shortly to help you understand their uses more closely. Any question, just ask!!

Follow up

If you want to know when new articles are released, subscribe yourself to the Google Android RSS feed. Otherwise, you can follow my research, articles and work on my professional Twitter account: jbeerdev.

Source Code

The source code with the minimum functionality can be found here:

Take pictures in Android source code


Comments

Showing all 93 comments
 
gregory Nov 18, 2011 5:13 PM
RE: How to Program the Google Android Camera to Take Pictures
yes, I had the right permissions set. though thankyou for reply.<br><br>i have solve this problem by totally removing eclipse&amp;sdk from my computer, putting it all in new directories and writting the applications again. dont know what was the problem, it came suddenly so I didnt know which of my actions to blame.
Andy Nov 18, 2011 4:05 PM
RE: How to Program the Google Android Camera to Take Pictures
That looks like a permission problem did you allow the correct permissions in the AndroidManifest.xml. file 3rd from bottom.
gregory Nov 11, 2011 5:38 PM
RE: How to Program the Google Android Camera to Take Pictures
hi, I have a problem. eclipse doesn't show any errorr but when I launch my application on emulator it immediatelly says "the application has stopped unexpectedly" -&gt; force close<br><br>and it happens on my mobile too. it happens with different camera application i made. any clue why?
Qewr Oct 28, 2011 12:31 PM
RE: How to Program the Google Android Camera to Take Pictures
Dein code ist bloss schrott
Sss Oct 27, 2011 6:13 AM
RE: How to Program the Google Android Camera to Take Pictures
i am trying your code with andorid 2.3.3 and it just hangs and says Activity Pictures is not responding?
Zekitez Oct 2, 2011 12:57 PM
Thank you
Thank you. This page helped to solve a problem where I used in a tab the camera preview with on top a canvas. Make sure you get the SurfaceView in the Activity OnCreate and then pass it to the preview class.
Ashish Sep 23, 2011 6:51 AM
any hints if i need to record video without Android's mediarecorder class?
Hi,
Your example worked flawlessly.. thanks.
Any hints if i need to record video without the mediarecorder class?

Thanks.
Tom Sep 20, 2011 11:31 PM
Image Display rotation fix!
Add the following line of code under the mCamera = Camera.open(); statement
mCamera.setDisplayOrientation(90);
The block of code should now look like this:
public void surfaceCreated(SurfaceHolder holder) {
Log.e(TAG, "surfaceCreated");
mCamera = Camera.open();
mCamera.setDisplayOrientation(90);

At least that fixes the DISPLAY of the image on the droid.
Deepesh Jain Aug 19, 2011 4:01 AM
imageData is always null
HI all ,I am able to run the code with any errors, after taking the pic i need to strore this pic in the gallery folder, But the problem is imageData is always null,Can any one help on this
deepesh Aug 1, 2011 8:58 AM
file not found exception
Exception for camera :-/sdcard/1312203454810.jpg (Permission denied)
W/System.err( 4931): java.io.FileNotFoundException: /sdcard/1312203454810.jpg (Permission denied)
Stephen Lacey Jun 27, 2011 1:28 PM
Camera image seems to be rotated
Thanks for the excellent guide and code.

I have integrated a camera function into my app based on this, but the image in the camera preview always seems to be rotated 90 degrees.

I then installed your sample app and found the same thing.

Any idea how I would get the camera preview to rotate to match the camera orientation?

Thanks!
Elth Jun 16, 2011 4:58 AM
picture problem on my galaxy S
Hi,

I had try to take picture with many source code and its work on AVD but when i try to run on my galaxy S the quality of camera is really bad. The camera is deformed like this screen :
http://imageshack.us/photo/my-images/830/device20110616104650.png/
But when i click for take the picture, the picture like normal.
Somebody have an idea ?

(sorry for my traduction, i'm french =) )
M.Balaji Mar 26, 2011 9:50 AM
need camera codes with defult pictures
need code for camera and that application having some default picture matches with taken image
Asyraf Mar 14, 2011 9:49 PM
Thank you very very very very much
Thank you for posting the LinearLayout code. Really appreciate it. My camera view start to display (^_^)V thank you
Jbeerdev Mar 3, 2011 7:09 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi joulesm

Did you import the complete proyect? or just took pieces of code? I have just tried it in my phone and it compiled and worked perfectly.
joulesm Mar 2, 2011 7:27 PM
error in onCreate
Hi, I'm trying out your code. In the onCreate, this line:
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);

This line is giving me the error: "id cannot be resolved or is not a field". Any ideas?
Thanks so much.
X10-Mini-Owner Mar 1, 2011 12:18 PM
YES
Hi,

yes - it works!
With my Sony X10-Mini.
Without any modifications of your *.zip :))

Very cool explanations!
Thanks a lot!
John Feb 3, 2011 5:28 PM
Nice tutorial
Just stumbled upon this tutorial on my quest to find some info about the camera in android. I don't know if it's my IDE that is borked or what (running the newest Android SDK and Eclipse 3.6.1) but no matter what I tried (even copying the code from the code snippets directly into my project the app kept fc'ing on my phone (HTC Hero). Then I read all the comments on this page and finally found the full project. After loading this into Eclipse it worked as intended.

But thanks for the tutorial anyways - was great to learn a bit about the camera anyways as a lot of the camera API isn't really documented from Googles side...
David Jan 20, 2011 10:52 AM
@JMS
I have an EVO 4G as well and mine crashed originally as well. The reason this happens is because there are specific sizes of the camera that we can request. This code here...

Camera.Parameters p = mCamera.getParameters();

p.setPreviewSize(w, h);

mCamera.setParameters(p);

...is setting the camera to a size that it doesn't support. To find the sizes supported, do this...

List<Camera.Size> list = p.getSupportedPreviewSizes ();

They are ordered from largest to smallest, so the largest will be...

Camera.Size size = list.get(0);

and then use...

p.setPreviewSize(size.width, size.height);

then set the parameters....

c.setParameters(p);

Hope that fixes it for you!
JMS Jan 14, 2011 9:44 AM
EVO 4G
He jbeer... stumbled across your post while on my endeavor to do a camera app. Really appreciate your time and the much needed information. I am a noob to Android development - JAVA even so I'm struggling to get through some things. I can run the app in an emulator but once I put it on the phone I get a force close. What tool or what direction should I head in here to help me diagnose why I'm getting a force close. I am in an Eclipse environment, my project is set up for min API8 and a 2.2 emulator... EVO has froyo on it as well. i think that's enough info.

Thanks a Bunch
sourav Sep 23, 2010 10:19 AM
picture not clear
hi jbeer thanks for the code and it works well,but while camera is on it doesnot show clear picture and when we took a picture,it will be a clear picture any idea why so? i am also using htc having device api version 3 .........awaiting ur response .
thanks !!!!1
GodIsGud Sep 9, 2010 3:34 PM
Why upside down
Why is the picture always upside down?
mohanb Aug 24, 2010 7:36 AM
Camera Program Android
Hey, I wrote the Camera Program which was given in this post and tried to execute in Emulator, but I am not able to catch the picture.
I implemented onClick Listener interface for SurfaceView , where in onClick() method I have overridden onPicturetaken() method and drawn the BitmapImage using drawBitmap() of canvas.

//The following is the piece of code I added to your code:
public void onClick(View arg0) {
if(arg0==mSurfaceView)
{
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
System.out.println("Pictureeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, opt);
// mSurfaceView.invalidate();


}
};

}

}

public void onDraw(Canvas c)
{
c.drawColor(Color.WHITE);
c.drawBitmap( bitmap, 10, 10, null);

}
Pedro Teixeira Aug 24, 2010 5:22 AM
A little help please
Hi..Thanks for this tutorial, helped me alot. Can you please just explain a little bit better the implemented methods for taking the picture? It's supose to take a picture when clicking on the screen?
I mean.. nothing is happening for me..
I don't get the picture.callback the onclick and the storebyteimage
tom Aug 4, 2010 5:16 AM
HTC Hero device
I manage to get the real device (HTC Hero) work by searching other forum for solution - comment the below line:
p.setPreviewSize(w, h);
in your code. the logcat show some camera filenotFoundException when try to switch camera mode.
Joe Aug 3, 2010 5:19 PM
Not working in Portrait mode with Droid
The Camerapreview is not displaying corretly in portrait mode on the motorola droid, however is does display correctly in landscape? How can I fix this without setting the orientation to horizontal because I need to know what orientation was in when I take the picture so i can rotate it when I save it. Thanks
Jbeerdev Jul 28, 2010 5:15 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi Tom

I have test it in my HTC Magic, and all is ok. Do you have the logcat trace so you can share the failure?
tom Jul 28, 2010 5:08 AM
real phone
thanks for the project, I try it in simulator and it work. but when I deploy to real phone (HTC Hero), it is not working ("the application Pictures (...) has stopped unexpectedly. Please try again "). Any clue ?
Jbeerdev Jul 28, 2010 3:03 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi everyone.

I have placed the full minimal and functional project here:

http://dl.dropbox.com/u/2534062/Pictures.zip

Hope it helps.
A.H Jul 23, 2010 6:55 AM
Do you have a project file for it
It is hard to understand here.Can you please put the project folder here.It will really help to understand.I am confused in layout section.
martin Jul 22, 2010 7:03 AM
Could not run code
Could you please post the full code since I an unable to run your code?
h3r3t1c Jul 5, 2010 7:31 PM
RE: How to Program the Google Android Camera to Take Pictures
For anyone getting the error saying setParamters failed in your manifest this is it should say to fix it:
<activity android:name=".CamaraView" android:screenOrientation="landscape"></activity>
HopsNBarley Jun 27, 2010 12:03 PM
Portrait
Has anyone figured out how to correct the duplicate overlapping images when the camera is in portrait? Works find in landscape.
scott Jun 22, 2010 7:06 PM
handling screen orientation issues
I found that adding this:

android:screenOrientation="landscape"

to you manifest file fixes most of the issues with the screen going weird when the user rotates the phone (keeps it from redrawing the screen to handle the new orientation)
Jbeerdev Jun 16, 2010 2:01 PM
RE: How to Program the Google Android Camera to Take Pictures
Just a comment:

The bright hub text editor to create articles has no way to insert "syntax highlighting" or formatting code.

Sorry for that.

That's why I have put the code snippets here:

http://snippets.dzone.com/posts/show/8685
Aaron May 11, 2010 10:16 AM
RE: How to Program the Google Android Camera to Take Pictures
Hey jbeer,

this article its really are to follow, for new Android developers. your not covering the full work flow for implementing a camera. i.e.

SurfaceHolder.Callback, OnClickListener is missing and if you just implements SurfaceHolder you get errors.

i must say i got really lost trying to do this. what a shame
Jbeerdev Apr 30, 2010 5:37 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi Naveen

Sorry for not answering you before.

About aspect ratio, try to resize the image after capture it. You can find good example of image resize here: http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
Or you can check the Camera Parameters:
http://developer.android.com/reference/android/hardware/Camera.Parameters.html

About the other issue you question me. Ok, the app takes a picture, save its, and then exits (if you use this as stand-alone app), but you have to glue it in your application, with other activities and elements. About the preview, is not implemented.
Naveen Bansal Apr 30, 2010 5:25 AM
Camera Application
Hi..
I am trying to run my camera applciation on development board.
It is working fine for once. When i ran my application in Emulator the preview started again after picture has been clicked.. But now... when i am running the same application on BoARD .. the preview runs once ... after clicking the first picture,... Preview does NOT start again.

Please Help.. and Please also tell me about how to Set
ASPECT RATIO
Jbeerdev Apr 30, 2010 4:21 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi All

I have re-tested the snippets and all works fine here. Here all the full source code:

http://snippets.dzone.com/user/Jbeer

And remember to put the permission in the Manifest:

<uses-permission android:name="android.permission.CAMERA"></uses-permission>

About the "memory exception"... thats creepy... When it happens to me, I have to reboot the device. If it happens to your emulator... don't know what could be. This kind of errors (memory exceptions) always drives me crazy...
Bryan Apr 29, 2010 9:28 PM
AVD out of memory
Hey, when I try to run this example code, my app crashes and returns an out of memory exception. The trace leads back to the Camera.open() method.

I think it may be the way my avd is set up. It is simply a v1.5 with hasCamera set to true. What am I missing?
Naveen Apr 29, 2010 8:10 AM
setAspectRatio
Please tell me how to set the Aspect ratio.??
I am working on Camera Apllication developemnt in android.
Eric Mar 31, 2010 10:10 AM
full project
Same as Debtaru Basak, It 'll be fine to have te full project in one shot, more easier to test

Think a lot
Zach Mar 3, 2010 4:26 PM
re:
So I solved the repeated pictures problem by commenting out the "finish()" method call at the end of onCreate().

Another bug: when I turn the phone orientation to be vertical, I get two smaller identical views of the camera that are displayed horizontally (so they look like they are sideways) and each take up half the screen. What I want is a vertical view of the camera...how do I accomplish this?

On a related note, when I turn the phone back to landscape mode, the picture fixes itself to look correct in landscape, I get the following in Logcat:

E/QualcommCameraHardware( 52): Invalid preview size requested: 480x800
D/QualcommCameraHardware( 52): value:310410, country value:310, country code:310
I/QualcommCameraHardware( 52): Set zoom=0
W/System.err( 1744): java.lang.RuntimeException: setParameters failed
W/System.err( 1744): at android.hardware.Camera.native_setParameters(Native Method)
W/System.err( 1744): at android.hardware.Camera.setParameters(Camera.java:619)
W/System.err( 1744): at com.code.CameraPreview.surfaceChanged(CameraPreview.java:130)
W/System.err( 1744): at android.view.SurfaceView.updateWindow(SurfaceView.java:460)


I'm pretty sure these are related. Any ideas? It's as if the phone always wants to be in landscape mode...

Zach
Jbeerdev Mar 2, 2010 2:48 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi Zach

Maybe you can try do it in the "mCamera.startPreview();" method, then store in some array structure the pictures taken (inside the onPictureTaken method). I have never tried, so let me know the result!
Zach Mar 1, 2010 11:34 AM
multiple pictures...
Hey again,

I have now gotten my program to upload an image to a server after it's taken, but I would like to be able to take multiple pictures; right now the application exits immediately after taking one picture.

I figure I should put some part of the program inside a while loop, but I'm not sure which part. Thoughts?

Zach
Jbeerdev Feb 28, 2010 2:17 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi again

True, I have to fix that. Thanks!
Zach Feb 28, 2010 2:03 PM
re: having an error
Ok I fixed it...you have a few bugs in your code. I think the line

setContentView(R.layout.camera);

should read

setContentView(R.layout.surface_camera);

Also in your file utilities you have "String expName" as an argument in the method storeByteImage so this line should be:

fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/" + expName + ".jpg");

I think that was giving people some errors.

Anyway, thanks for the answer. I'm working on an application that uploads captured pictures to a server for image processing, so I will probably have more questions for you in the next few days as I get deeper into development.

Zach
Jbeerdev Feb 28, 2010 1:40 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi Zach!

Thanks for the feedback. That's true, I have to put the snippets in the article.

About your problem, in the "setContentView" method, you have to place the layout element you have created to hold the surfaceview. For example, if you created a "camera.xml" file inside res/layouts folders you have to put:
setContentView(R.layout.camera);

Other hint. In layouts never use uppercase, Android will not recognise the files and it will fail.
zach Feb 28, 2010 1:16 PM
having an error
Hey,

Thanks for this tutorial, it was pretty helpful - you should post all links to all of the code snippets inside the tutorial though, I had to dig through the comments to find them.

I've encountered a few errors which I've figured out and the last one before my code will compile completely is in the code line

setContentView(R.layout.camera);

gets the error R.layout.camera cannot be resolved.

What is the fix? I'm pretty new to android development so I dont have a great grasp of how the xml file interacts with the .java files yet.

Thanks for your help!

Zach
Jbeerdev Jan 26, 2010 2:59 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi Ting again!

I have not tested it, but try this piece of code;

videoRecorder = new MediaRecorder(); videoRecorder.setPreviewDisplay(holder); videoRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); videoRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); videoRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); videoRecorder.setMaxDuration((int) TIME_YOU_WANT); videoRecorder.setVideoSize(320, 240); videoRecorder.setVideoFrameRate(15); videoRecorder.setOutputFile(output_file_path);

videoRecorder.prepare();
videoRecorder.start();

The point is the "holder", that is the same surface I have used in the "Camera".

Anyway, as I said, I have not tested this functionality.
ting Jan 26, 2010 1:49 AM
How to program android to take picture
Hi Jbeer,

If i wish to use the code to do video recording, is it possible? What should i do?
Jbeerdev Jan 18, 2010 7:40 AM
RE: How to Program the Google Android Camera to Take Pictures
Ummm... Maybe you have to wait until google releases that version for our devices (I have a HTC Magic too, with Vodafone, here in Spain).
ting Jan 18, 2010 7:31 AM
SDK update
Hi Jbeer,

I using HTC Magic to develop application. May I know that is it possible to upgrade the android 1.6 to android 2.0.1??
Jbeerdev Jan 18, 2010 7:22 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi ting

I have worked with Bluetooth before, but no with Android, I have worked with J2ME.

If I start working with Bluetooth in Android, I will write about it here.

Anyway, Im not sure if Bluetooth is working in SDK versions lower than 2.0... I have to check it out.
ting Jan 18, 2010 7:16 AM
Bluetooth Sample code
Hi Jbeer,

Thanks a lot. May i know that u work for any Bluetooth data transfer sample codes. I wish to create an application to connect to other Bluetooth devices. May I seek u advice?
Jbeerdev Jan 18, 2010 6:20 AM
RE: How to Program the Google Android Camera to Take Pictures
Hi ting

You can do the following:

Using the code I gave you to create the cameraView xml file (http://snippets.dzone.com/posts/show/8687) you can replace the "LinearLayout" and use a "RelativeLayout" for example, and put elements (buttons, whatever you want) in the screen. The surfaceView is the "camara preview".

Try it, and let us know.
ting Jan 18, 2010 6:11 AM
How to program the google android camera to take picture
Hi Jbeer,

Thanks for u response. If i wish to create a button widget in xml layout to capture the picture and not by touching the screen, what should i do?

Thanks for u advice.
Jbeerdev Jan 18, 2010 3:05 AM
RE: How to Program the Google Android Camera to Take Pictures
About taking many pictures, well, the code you have there is one piece of the puzzle, you have to combine it with the other pieces in your application to create a more complex functionality.

About the "button" functionality, I will have to have a look at it, because I use the

public void onClick(View arg0) {

mCamera.takePicture(null, mPictureCallback, mPictureCallback);

}

event (OnClick in the Screen).

You will have to implement the "OnClick" but in a hardware button (the trackball, for example).
Jbeerdev Jan 18, 2010 3:00 AM
RE: How to Program the Google Android Camera to Take Pictures
HI ting

try if the fonder in this variable exits:

sdImageMainDirectory

if not, create it, maybe this is the problem.
ting Jan 17, 2010 11:29 PM
How to program the google android camera to take picture
Hi Jbeer,

Thanks Jbeer, finally i did manage to take picture using android emulator camera, but figure that i just possible to take one picture at a time and the application will stop automatically. I wish to know whether is it possible to take many picture without exit the application. And one more thing, the picture is taken by touch the screen, if i want to take picture by touching a button, is it possible to do that? What should i change on the code.

Thanks. You really help me a lot. You did provide an excellent website to help those who needed.
ting Jan 17, 2010 6:44 PM
How-To Program The Google Android Camera To Take Pictures Read more: http://www.brighthub.com/mobile/google-android/articles/43414.aspx?p=2#comments#ixzz0cuu9k7WV
Hi Jbeer,

Thanks for the response. beforehand i initialize the the string nameFIle = null and the application stop unexpectedly. Now i try to name to variable simply to be string nameFile = "abcd"; but the application still stop unexpectedly. May u simply give an example to solve this problem?

Thanks.

yassin Jan 17, 2010 5:44 PM
CameraView
Ok,

I will dig more and let you know my final solution.

Thanks alot

Yassin
Jbeerdev Jan 17, 2010 5:39 PM
RE: How to Program the Google Android Camera to Take Pictures
Ummm. I don't think its possible to do what are you saying. I have never heard.

About the picture in the SD, did you get any error? Maybe you have to create some "trace" to see what's going on. Do some debugging, check variables, etc...
Yassin Jan 17, 2010 5:32 PM
CameraView
Yes,

Take a picture in the background with no user interaction and no shutter sound please...

Please, I need this one bad...

Also, I am not seeing the picture taken with CameraView???

Thanks

Yassin
Jbeerdev Jan 17, 2010 5:17 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi again

When you say "take a picture programmatically behind the scene" do you mean taking the picture "in the background" with no user interactuation and no "camera screen" show?

I will consider the MMS tutorial. Im working in other stuff, but I think it will be interesting.

Yassin Jan 17, 2010 5:13 PM
CameraView
Hi Jbeer,

I removed it and replaced it with = "anystring" and it now takes a picture when you touch the screen. But, I don't see the picture taken on my SD card.

Also, the reason I need this program is I want to take a picture programmatically behind the scene not by touching the screen, save it and send it via MMS.

If you can help me with this I will forever be greatfull.

So sending MMS programatically with any file/media type (audi, video, image) attachment will be a GREAT tutorial. There is no program on the web that shows this in a step by step, or sending MMS programatically at all. I search and search and could not find it.

Thanks

Yassin
Jbeerdev Jan 17, 2010 4:46 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi Yassin

Umm, Im sorry for that. This piece of code was not supposed to be there. My mistake. Delete it, and replace its appearance to a string you want.
Yassin Jan 17, 2010 4:28 PM
NullPointer Exception
Hi Jbeer,

Thank you again.

Here is what is causing the null pointer exception

mExpNumber = extras.getString("EXP_NUMBER");

Yassin
Jbeerdev Jan 17, 2010 3:55 PM
RE: How to Program the Google Android Camera to Take Pictures
Ok, you have a NullPointer exception in the Line 37 of CamaraView

Caused by: java.lang.NullPointerException
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at com.somforce.CamaraView.onCreate(CamaraView.java:37)

check it, what do you have in this line? something not initialized?
Jbeerdev Jan 17, 2010 3:51 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi ting

Did you put the name of your image in the "nameFile" variable?

Yassin Jan 16, 2010 11:02 PM
CameraView
I get NullpointerException. But I am using the Unlocked G1.

Here is the error
...

01-16 23:10:27.526: ERROR/AndroidRuntime(625): Uncaught handler: thread main exiting due to uncaught exception
01-16 23:10:27.546: ERROR/AndroidRuntime(625): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.somforce/com.somforce.CamaraView}: java.lang.NullPointerException
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.app.ActivityThread.access$2100(ActivityThread.java:116)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.os.Handler.dispatchMessage(Handler.java:99)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.os.Looper.loop(Looper.java:123)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at android.app.ActivityThread.main(ActivityThread.java:4203)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at java.lang.reflect.Method.invokeNative(Native Method)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at java.lang.reflect.Method.invoke(Method.java:521)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at dalvik.system.NativeStart.main(Native Method)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): Caused by: java.lang.NullPointerException
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at com.somforce.CamaraView.onCreate(CamaraView.java:37)
01-16 23:10:27.546: ERROR/AndroidRuntime(625): at an
ting Jan 16, 2010 8:00 PM
About full code u given
Hi Jbeer

currently i'm using android 1.6 to run the codes. I have create the class FileUtilities and put in the code as provided. But there an error on this line.
sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");
it state that nameFile is not been initialized. Then i initialize the string nameFile = null and try to run the code. The code shows no error but when i test it on the emulator, the application stop unexpectedly. May I need u advice?

Thanks.
Yassin Jan 16, 2010 6:15 PM
Tutorial Requests
Hi Jbeer,

Thanks for your help. I have several suggestions about tutorials you can write.

1) How to programmatically send MMS. (Please show all that is needed including the TO address code), attach any file type (image, audio etc)

2) Take a picture programmatically and send it via MMS or SMS (show both if you can).

3) Take several pictures and display them in GridView tiled and/or in a view that shows images across, but once you select the thumbnail, can be displayed at the buttom.

3) How to Animate a small image so it can move across the screen and bounce back on the edges of the screen based on the x, y coords. This will help people who want to design games. Also make two images so they know where each image is in the view.

That is a start for now.

Thank you for all your help.

Yassin
Jbeerdev Jan 16, 2010 3:16 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi Yassin again

Well the code I have put there in not the full code to make it work, just the "guide line". You need, for example the EXTRA to set the person you want to send the image, or the piece of code you need to send the MMS.

All about "Intents" and "SENT_TO" options, I suggest you to have a look to this:

http://developer.android.com/guide/topics/intents/intents-filters.html

About the GridView I will have to check it. Maybe I could write something about all this. Anything in particular? This way I can explain myself a bit better.
Yassin Jan 16, 2010 2:58 PM
Camera View
Thanks a million for the quick response.

So see if I understand this correctly, here is what I am doing...

I am using your code...found here...http://snippets.dzone.com/user/Jbeer

1) CamaraView --- class
2) FileUtilities --- class with (storeByteImage) method.
in this storeByteImage method, image is saved as .jpg.

So now I am creating another method that is to send the MMS with the image like this.

public void sendMMS() {

String url = "/sdcard/myImages/myimage.jpg";

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra("sms_body", "here put the body");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(url));

}

??? What size image will your program save? so the SendMMS can send it properly.
---------

Also, for the GridView

I need my pictures to look like this...
http://developer.android.com/guide/tutorials/views/hello-gridview.html

Instead of hardcoding the images, how can I read the images in a specific directory for this app.

Thanks alot again, I really appreciate it.

Yassin





Jbeerdev Jan 16, 2010 2:34 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi Yassin

Once you have the file in your SD, you can do whatever you want with it, like send it to MMS or add as background in a View.

Send it by MMS:
-You need to create an Intent with the option "ACTION_SEND":
Intent sendIntent = new Intent(Intent.ACTION_SEND);
-set the type as :
sendIntent.setType("image/png");
-you can set the body of the mms if you want:
sendIntent.putExtra("sms_body", "here put the body");
-Important!: set the image:
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(url));
where url is where the image is stored: example:
"/sdcard/myapp/myimage.png"

This is the basic.

About putting your image in a View, maybe as a background you can do this:

Create a Drawable object form your image:

Drawable drawable = Drawable.createFromPath(imagePath);
where imagePath is where the image is stored: example:
"/sdcard/myapp/myimage.png"

and in your view objet you do

GridView gView;
...(initialize the object)
gView.setBackgroundDrawable(drawable)

I have not tested this last lines, let me know if it works!!
Jbeerdev Jan 16, 2010 2:14 PM
RE: How to Program the Google Android Camera to Take Pictures
Hi ting

"FileUtilities" was a class I created to work with files, you can find the code in this place:

http://snippets.dzone.com/posts/show/8685
Yassin Jan 16, 2010 1:50 PM
CameraView
Hi JBeer,

Thank you for being helpful to all.

I have read your Camera View tutorial, but I need little more direction..

1) I need to be able to take an image, then send it via MMS right away.
2) Save the image in the phone. Your tutorial here ( http://snippets.dzone.com/user/Jbeer), has take picture and save in another method, but I am not sure how to combine the two codes.

3) Finally, I want to display the images I take via GridView on one of my tabs in my App.

Thank you so much for your time.
ting Jan 16, 2010 7:34 AM
About full code u given
hi Jbeer

I am new to code android. May I know how to use the code u had been given. I just use the camera activity and xml code for testing the result. And i did find error on this line.
FileUtilities.StoreByteImage(mContext, imageData, 50, mExpNumber);
The error show on the FileUtilities, May I seek advice from u?
Jbeerdev Nov 21, 2009 3:14 PM
RE: How to Program the Google Android Camera to Take Pictures
Ah!
I see now! :)

Great you could it make work!
Kaitlin Nov 20, 2009 11:04 AM
RE: Saving pictures in SDCard
Hi Jbeer-

It was just a syntax error. Here's the correct format:

File sdImageMainDirectory = new File("/mysdcard/myImages/") ;

Thanks!
Kaitlin
Kaitlin Nov 20, 2009 10:27 AM
RE: Saving pictures to SD Card
Hey Jbeer -

It's still not working. I think the problem is that it's reading the "/sdcard/myImages" as a string and not as a file path name. I'm not sure how to save to a file, but I'll keep searching for different ways. Let me know if you have any ideas.

Thanks,
Kaitlin
Jbeerdev Nov 20, 2009 2:57 AM
Saving pictures in SDCard
Hi Kaitlin again!

Have you check my snippet?

http://snippets.dzone.com/posts/show/8685

Ummm... I have not try it, but maybe usig "sdcard" in lowercase it will work. Its posible that Android file system is case-sensitive.... a "SDCard" folder may not be the same as a "sdcard".

Anyway, try it! and let me know.
Kaitlin Nov 19, 2009 10:51 PM
Save to File
Hey jbeer,

Thanks for the reply, that was really helpful. I have another question with regard to saving the picture to the SD card. This is what I have, but there's an error over the "\SDcard\Images\". Do you have any suggestions? Thanks a lot!!

File sdImageMainDirectory = "/SDCard/Image"
Jbeerdev Nov 19, 2009 2:52 AM
Icicle Stuff
Hi Kaitlin!

The "icicle" object (From "Bundle" class) is a parameter that is always passed to the onCreate in the Activities. In some places is called "saveInstance" here its called "icicle". This parameter is a way to "pass information to the Activity" when creating it. I have not think about it much...because it always have been there, but I suppose that It must be related too with the "Bundle.getExtras()" method. (A way to pass parameter from one Activity to Other).

Dont know if that answered your question...
Kaitlin Nov 19, 2009 2:35 AM
Question:
Hi Jbeer- I just have a question about what the icicle term is in the onCreate() method? Where is that defined within your code? I know that in a lot of code people use 'Bundle savedInstanceState' and I'm wondering about that. Thanks!
Jbeerdev Nov 13, 2009 2:43 AM
About Camera Notification
Hi saifuddin.

Ummm... I will have to research about what you tell me. I dont know, nowadays how to do it. Anyway have you looked in the Android Api Page?

http://developer.android.com/reference/packages.html

Maybe you found something. Anyway, If I see anything you could use, I will write about it.
Jbeerdev Nov 13, 2009 2:39 AM
Full codes
I have been searching for the code: Here you have

Camera Activity:
http://snippets.dzone.com/posts/show/8683
FileUtilis:
http://snippets.dzone.com/posts/show/8685
XML:
http://snippets.dzone.com/posts/show/8687

And dont forget to put the following in the AndroidManifest!!:

<uses-permission android:name="android.permission.CAMERA"/>

Hope it helps
Martin Nov 13, 2009 2:20 AM
Camera with Flash
I concur with Debtaru and tinyang, I'm finding it hard to find much about camera app development and this is the best so far...by far! Thanks, I would just like to know if there full code is available, and/or hints on using the flash?
saifuddin Nov 12, 2009 6:35 AM
RE: How to Program the Google Android Camera to Take Pictures
hi jabeer

m new to android
my task is like i have to disable camera programmetically

when ever end user opens his/her mobile camera I want notification for that and then have disable it

so far i ahve found only broadcast reciever for camera button press and not for camera open
(I want notification when user opens mobile camera).

can u help me out for that
Jbeerdev Sep 14, 2009 4:04 AM
Jbeer
Debtaru Basak - Maybe something is missing. Anyway, I have to look for some place to put the fullcode, highlighted and commented. When I have the place, I write about it here.
tinyang Aug 22, 2009 1:50 PM
Great info!!
Can't wait for the next article. And I agree with Debtaru that it would also be helpful if you posted all of the code together.
Debtaru Basak Aug 3, 2009 5:07 AM
Could not run the code
Could you please post the full code since I an unable to run your code?
 
blog comments powered by Disqus
Email to a friend