In this example we are going to cover of basics of taking picture with you camera on your android device and show it on screen after taking it.

ButterKnife library

First we add our favorite ButterKnife library in our build.gradle app file and sync the project:

AndroidManifest XML:

We must add camera permissions to our AndroidManifest in order to call the camera in our app:

 

The Main Activity XML:

In this Activity, there is nothing more than to show the captured image on screen. Because of that we use only one defined ImageView, one descriptive TextView and one Button for calling the camera:

 

The Main Activity Java:

Also in the Main Activity we call the camera on button click by starting an activity by intent for result. The app is starting the camera and receive the captured photo as a result.

In on activity result we compare if our request code (TAKE_PICTURE) is used, and by that we get the data as result for taking the photo with our camera:

Of course here we have some run-time permissions for the camera (used from Android API 23) and that will be covered in later examples. We will not focus on permissions in this example.

When we get the requested image it is not received as image but as data. From that data we must extract the image and map it on Bitmap object. This is done using (data).getExtras()).get(“data”), and Objects.requireNonNull before it, is safe check if data is null. After we map it on to our Bitmap object, thumbnail, then we set it on our previously created ImageView called image by calling the setImageBitmap method and passing thumbnail as an parameter.

Here is the whole MainActivity:

 

You can get the whole project on GitHub BuktopMKD/TakePictures

 

 

 

 

 

 

Spread the love

Leave a Reply

Your email address will not be published.