Nowadays camera become one the major features that lot of apps provides. You can see the camera feature excessively used in apps in the area of food, social networking, video sharing apps. Integrating camera in your app is very simple task if you are not expecting a custom UI.

In this article we are going to see how to integrate the basic camera feature that takes pictures or record video through your app.

android-recyclerview-databinding-example

1. Android Camera API

There are two ways to integrate the camera module.

  • Using In-built Camera App:
  • The easiest way to integrate camera feature is, use the in-built camera app that comes with the device. To launch the camera app, you just need to pass the appropriate intent with necessary flags. Rest will be taken care by the camera app and it will return the data (image or video) to your app. The disadvantage of this method is, you can’t customize the camera interface as you would be launching third party camera app.

  • Writing Custom Camera App:
  • Building your own camera module takes some effort as you need to build everything from scratch beginning with user interface to integrating camera API (rending camera preview, toggling front and back cameras, flash, focus etc.,). But the advantage over here is, you can build the uniform camera UI which will be same for all the users. You can see custom camera in apps like Instagram, Facebook etc.,

Below is the demo app that we gonna build in this article. The UI is very minimal with two buttons and an area to preview the captured image or video.

android-camera-tutorial-capture-image-record-video

Now let’s start by creating a new project in Android Studio.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Open app/build.gradle and add Dexter dependency to request the runtime permissions.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // ...

    // dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

3. Add the below resources to respective strings.xml, colors.xml and dimens.xml

<resources>
    <string name="app_name">Android Camera</string>
    <string name="action_settings">Settings</string>
    <string name="preview_description">Image and Video preview will appear here</string>
    <string name="btn_take_picture">Take Picture</string>
    <string name="btn_record_video">Record Video</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#1fb49c</color>
    <color name="colorPrimaryDark">#1fb49c</color>
    <color name="colorAccent">#FF4081</color>
</resources>
<resources>
    <dimen name="activity_margin">16dp</dimen>
    <dimen name="dimen_8">8dp</dimen>
</resources>

4. Under res, create a new folder named xml. Inside xml folder, create a new xml file name file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

5. Open AndroidManifest.xml and add CAMERA, WRITE_EXTERNAL_STORAGE and RECORD_AUDIO permissions.

Here we also added camera feature that defines the rules to list the app on Playstore. If we keep android:required=”true”, Google Playstore won’t let the users to install the app on the devices that doesn’t have camera feature. Incase of false, the app will be listed but camera feature is optional.

We also need <provider> tag to prepare the file paths properly across all the android platforms.

<uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.androidcamera">

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

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

6. Create a class named CameraUtils.java and add the below methods. This is a helper class that provides necessary methods that we need in our camera module.

  • refreshGallery() – Refreshes the image gallery after taking a new picture or video so that they will be instantly available in the gallery. In older android devices, gallery won’t be refreshed until the device is rebooted.
  • checkPermissions() – Checks whether all the permissions are granted or not. This would be called before requesting the camera.
  • getOutputMediaFile() – Create a new file in gallery and returns the file. This reference will be passed to camera intent so that newly taken image / video will be stored in this location.
  • optimizeBitmap() – Compresses the bitmap before displaying it on UI to avoid the OutOfMemory exceptions.
package info.androidhive.androidcamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CameraUtils {

    /**
     * Refreshes gallery on adding new image/video. Gallery won't be refreshed
     * on older devices until device is rebooted
     */
    public static void refreshGallery(Context context, String filePath) {
        // ScanFile so it will be appeared on Gallery
        MediaScannerConnection.scanFile(context,
                new String[]{filePath}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
    }

    public static boolean checkPermissions(Context context) {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Downsizing the bitmap to avoid OutOfMemory exceptions
     */
    public static Bitmap optimizeBitmap(int sampleSize, String filePath) {
        // bitmap factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = sampleSize;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * Checks whether device has camera or not. This method not necessary if
     * android:required="true" is used in manifest file
     */
    public static boolean isDeviceSupportCamera(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * Open device app settings to allow user to enable permissions
     */
    public static void openSettings(Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Uri getOutputMediaFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    }

    /**
     * Creates and returns the image or video file before opening the camera
     */
    public static File getOutputMediaFile(int type) {

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

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

        // Preparing media file naming convention
        // adds timestamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MainActivity.MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + "." + MainActivity.IMAGE_EXTENSION);
        } else if (type == MainActivity.MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + "." + MainActivity.VIDEO_EXTENSION);
        } else {
            return null;
        }

        return mediaFile;
    }

}

7. Now open the layout files of main activity i.e activity_main.xml and content_main.xml and add the below layout code. Here we are defining couple of Buttons, ImageView and VideoView to preview the captured media.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/activity_margin"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_desc"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/preview_description"
            android:textSize="15dp" />

        <!-- To display picture taken -->
        <ImageView
            android:id="@+id/imgPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:visibility="gone" />

        <!-- To preview video recorded -->
        <VideoView
            android:id="@+id/videoPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:visibility="gone" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <!-- Capture picture button -->
        <Button
            android:id="@+id/btnCapturePicture"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dimen_8"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:foreground="?attr/selectableItemBackground"
            android:text="@string/btn_take_picture"
            android:textColor="@android:color/white" />

        <!-- Record video button -->
        <Button
            android:id="@+id/btnRecordVideo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dimen_8"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:foreground="?attr/selectableItemBackground"
            android:text="@string/btn_record_video"
            android:textColor="@android:color/white" />
    </LinearLayout>
</LinearLayout>

8. Finally open MainActivity.java and modify the code as shown below.

  • In onCreate(), the availability of the camera is checked using isDeviceSupportCamera() method and activity is closed if the camera is absent on the device.
  • On button click, checkPermissions() method is used the check whether required permissions are granted or not. If not granted, requestCameraPermission() method shows the permissions dialog to user.
  • captureImage() open the camera app to capture the image.
  • captureVideo() opens the camera app to record the video.
  • Once the media is captured, the image or video will be saved to gallery. previewCapturedImage() and previewVideo() renders the captured image / video on the screen.
  • showPermissionsAlert() – Shows an alert dialog propting user to enable the permissions in app settings incase they are denied permanently.
package info.androidhive.androidcamera;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

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

    // key to store image path in savedInstance state
    public static final String KEY_IMAGE_STORAGE_PATH = "image_path";

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

    // Bitmap sampling size
    public static final int BITMAP_SAMPLE_SIZE = 8;

    // Gallery directory name to store the images or videos
    public static final String GALLERY_DIRECTORY_NAME = "Hello Camera";

    // Image and Video file extensions
    public static final String IMAGE_EXTENSION = "jpg";
    public static final String VIDEO_EXTENSION = "mp4";

    private static String imageStoragePath;

    private TextView txtDescription;
    private ImageView imgPreview;
    private VideoView videoPreview;
    private Button btnCapturePicture, btnRecordVideo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        txtDescription = findViewById(R.id.txt_desc);
        imgPreview = findViewById(R.id.imgPreview);
        videoPreview = findViewById(R.id.videoPreview);
        btnCapturePicture = findViewById(R.id.btnCapturePicture);
        btnRecordVideo = findViewById(R.id.btnRecordVideo);

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

            @Override
            public void onClick(View v) {
                if (CameraUtils.checkPermissions(getApplicationContext())) {
                    captureImage();
                } else {
                    requestCameraPermission(MEDIA_TYPE_IMAGE);
                }
            }
        });

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

            @Override
            public void onClick(View v) {
                if (CameraUtils.checkPermissions(getApplicationContext())) {
                    captureVideo();
                } else {
                    requestCameraPermission(MEDIA_TYPE_VIDEO);
                }
            }
        });

        // restoring storage image path from saved instance state
        // otherwise the path will be null on device rotation
        restoreFromBundle(savedInstanceState);
    }

    /**
     * Restoring store image path from saved instance state
     */
    private void restoreFromBundle(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_IMAGE_STORAGE_PATH)) {
                imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
                if (!TextUtils.isEmpty(imageStoragePath)) {
                    if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + IMAGE_EXTENSION)) {
                        previewCapturedImage();
                    } else if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + VIDEO_EXTENSION)) {
                        previewVideo();
                    }
                }
            }
        }
    }

    /**
     * Requesting permissions using Dexter library
     */
    private void requestCameraPermission(final int type) {
        Dexter.withActivity(this)
                .withPermissions(Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {

                            if (type == MEDIA_TYPE_IMAGE) {
                                // capture picture
                                captureImage();
                            } else {
                                captureVideo();
                            }

                        } else if (report.isAnyPermissionPermanentlyDenied()) {
                            showPermissionsAlert();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();
    }


    /**
     * Capturing Camera Image will launch camera app requested image capture
     */
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (file != null) {
            imageStoragePath = file.getAbsolutePath();
        }

        Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    /**
     * Saving stored image path to saved instance state
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
    }

    /**
     * Restoring image path from saved instance state
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
    }

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

        File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_VIDEO);
        if (file != null) {
            imageStoragePath = file.getAbsolutePath();
        }

        Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

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

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

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

    /**
     * Activity result method will be called after closing the camera
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // Refreshing the gallery
                CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // Refreshing the gallery
                CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

                // video successfully recorded
                // preview the recorded video
                previewVideo();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    /**
     * Display image from gallery
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
            txtDescription.setVisibility(View.GONE);
            videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);

            Bitmap bitmap = CameraUtils.optimizeBitmap(BITMAP_SAMPLE_SIZE, imageStoragePath);

            imgPreview.setImageBitmap(bitmap);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * Displaying video in VideoView
     */
    private void previewVideo() {
        try {
            // hide image preview
            txtDescription.setVisibility(View.GONE);
            imgPreview.setVisibility(View.GONE);

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(imageStoragePath);
            // start playing
            videoPreview.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Alert dialog to navigate to app settings
     * to enable necessary permissions
     */
    private void showPermissionsAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Permissions required!")
                .setMessage("Camera needs few permissions to work properly. Grant them in settings.")
                .setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        CameraUtils.openSettings(MainActivity.this);
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }
}

Run and test the app on a real device. You can see the app working as shown in the demo screenshots.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Sukumar

    Nice Example

  • Nice tutorial

  • Jeffy Lazar

    Thank you so much …thank you so much …..thanks a lot man …you are the best 🙂 🙂

  • Sagar Maiyad

    Sorry, but you are not using any Camera API.. its buitin camera..

    • I’ll change the title

      • Sagar Maiyad

        Okey, but can you tell me, is it working in all devices or not.??

  • Ajay Patel

    Your site now looks like songs.pk, its quality is not same as previous one. Like songs.pk your site full of adverts. It really sucks 🙁

    • I need some money to maintain site right ?

      • suncap

        I will click on all your adverts

        • Hi Suncap, Thanks for the help. But if we click ads intentionally my ads account will be cancelled 🙂

          • Connery Sean

            Hey I like your site !
            Keep up the good work

          • Jeffy Lazar

            ads are not of any problem …we dont even notice the ads as long as you keep posting such amazing and yet so easy to understand Android Tutorials.

            Keep up the great work 🙂 🙂

          • Krunal Doshi

            Start Premium Tutorial that only Premium users can access.

      • maulik

        we all are eagerly waiting for the Design and Tips section!

        • Yeah, they are under construction…

          • Steffy

            Sir do you use any cms ?

      • suncap

        AdsBlock+ FTW !!! 😛

  • Sagar Maiyad

    Have you any Example related to Camera API..?? if, then please publish here.. it will very useful for all and specialy for me.

  • Jumman

    How can I crop from camera preview with bounding box for selecting the region before capturing the images? like “Translanguage OCR” (https://play.google.com/store/apps/details?id=com.translanguage.free.version&hl=en) ,please help me regarding this .thanks

  • Lakshmi Reddy Kanneti

    sir you r mention fileurl in path.where is the image are video store.i want to store a capture images are videos in remote server.how can i do that. i am new for android .give me a start up .and also i am using that images and videos to send a message like whatapp.

    • Connery Sean

      My guess would be that you have to store your Images on your mobile first, and than push them online using some other technology to comunicate with your web server

      • Correct!

        • koko landry

          what are those technologies that I can use to get my picture on a remote server? i really need this for my project. can u please help?

  • Steffy

    Nice tutorial ! Sir do you use any CMS for this website ? Its awesome !

  • sakthivel

    thanks good tutorial. my small request make it android seekbar for value increment and decrement tutorial.
    best thanks
    sakthivel

    • sdfgh

      hhhhhh

  • Tulai Paul

    Such articles may prompt the mobile ad network companies and their apps and games developers to provide apps and games that are based on live camera. The list of such companies have been increasing constantly like admob, revmob, chartboost, tapjoy, adcolony, appnext, inmobi and so on

  • Joey

    Great tutorial man! Thnx! But do you know why my images show up with the default file names? The code renames video files, that’s good! Also, i can’t move the images to a custom folder? Hope you can help me!

  • mangesh kaduskar

    I took video from camera but now i want to upload it to YouTube. Will you please give me tutorial of how to upload video to YouTube.

  • Pablo

    Ravi I am getting an error:
    Pictures work just fine, but when I try to record video, the camera is launched but when I stop recording the app crashes, any ideas? I am running it on a 2.3.6 android version.

    • Shri Kant

      same problem here.

      • dhnjy 18

        Am also facing the same problem. did you find any solution. plz tell me

  • Douglas Roos

    How can i change the resolution and quality of the photo because when i send the photo to my webserver takes a long time, the photos have a size of 2mb or more.

    • Hari Haran Ayyappan

      Hi Roos , In what format you are sending the pics to server

      • Douglas Roos

        Hi Hari, i’m sending the photos in JPG format through MultiPartEntityBuilder, i’ve solved the problem downsampling the photo from the bitmap, rewriting the original photo and sending it to the server.

        • Hari Haran Ayyappan

          MultiPartEntity means are you using apache http multi entity jars? I am decompressing bitmap and sending .when i am decompressing , and subimtting to server i am getting out of memory exception. Did you experience this issue

  • Ugur Cakmak

    I’m triggering image capture intent from a custom dialogs button. After I succesfully saving the image to sdcard, application restarts and my dialog dissappears. I don’t want to restart my application, it’s not I want. I simply want after capture, return to where I was. How can I do that ?

    • Uğur Çakmak

      I commented out InstanceState Methods and now I’m fine. but in order to save my images in portrait mode, I should take a picture in landscape mode. I want to save images in proper modes like portrait in portrait, you know the rest. any suggestions ?

  • Gilbert

    Great tutorial man

  • jj

    this tutorial isn’t on the custom camera i found a better one here http://appskort.com/android-camera-tutorial

    • Ravi Kant chauhan

      brother can u send me complete code with directory structure for only camera activity..that means i want to take a pic and want to upload to the server..pls brother send me

      ravikantchauhan009@gmail.com

    • Carlos

      it doesn´t work in Tablet Nexus 7, because it has no SD card !!

      • Carlos

        Your app works amazing in my Nexus 7 – 2013 !!, thanks Ravi

  • Ankita Patel

    sir how to integrate this camera code in to all type of barcode reader in android

  • Stefan

    Whenever I start the app there is a black background until I click the button… Afterwards it’s working just fine… Does anyone know this problem?

  • Poojan Sharma

    Hi Ravi,
    I’m having some problem, i’ve implemented your code into my app but i’m confused as to how to store the captured image into my local storage. Please help me on this.

  • gautam behera

    Hello,
    I ran your code but I am not able to get a portrait image. When I take an image in portrait it becomes landscape in the app.
    So is it possible to get a portrait image.

    • Dhruvit Darji

      that is the bug which is already reported in android community and still they are working to fix it.. some people suggest to use EXIF techniques but be frank then it is not working in most of devices it always returning 0 rotation… if you have found any solution then plz let me know.. i badly require that…

  • Derdus

    Your code works perfectly well, but i am not able to capture the video capture. Help me please

  • Tyler

    Hello, my phone does not have a sd card(at least no sd card slot) so where would it be storing my pictures when I take them?

    Thank you,
    Tyler

  • Jekyll Bermeo

    Hello how will i fetch the captured image path?

  • koko landry

    nice tutorial. how do i upload pictures/videos to a remote server ? this will be of much help. tx

  • Andre Piper

    How do I set the recording limit, I didn’t see that in the code.

  • Kinjal Patel

    how we tak more than one shots programatically for android custom camera?

  • emiliano

    Hi, how can i adapt this code to use inside fragment? Thanks.-

    • Muaaz Odabashi

      any luck?

  • Mona Elgnedy

    Plz , If I want camera hidden and silent ?? how

  • Sinan

    How can I save the captured image on a server (localhost) instead of the sd-card?

    • Walter Reyes

      You would also need to make an api to handle the http calls. This is not too difficult with php and slim framework

      • Sinan

        Hi Walter,
        Thanks for your answer. But are you able to provide me some helpful links or tutorials ?

  • Gabriel Galang

    how could i save this on database sqlite???

    and anytutorial for camera to blob then to sqlite / sqlite to imageview 😀

    • golla priyanka

      hie if u got the answer please explain me

      • Why do you want to store the image in SQlite?

  • Paradisos

    Can please someone tell me what the “Activity request codes” is and why do I have to add a number ?
    I don’t see any use after….

    • may be since it is accessing camera API it may be response code like HTTP respnse
      i guessed answer with http response
      pls go through the Camera API in docs!

  • Carlos

    Excellent tutorial Ravi, congratulations. Please, let me do it a question. How could I add effect image to you camera?, for example color gray, sepia toning in Android NDK C++/C?.
    Regards,
    Carlos

  • Carla

    my videos and photos are not saved, do I have to adjust some code?

  • jason

    Hi thx for this great tuto. Plz how can we store the captured photo or video directly on mysql database and how can we resize the picture before storage !!!!

    • ubro

      Any answer Ravi plz for this question ???

    • Jasson Faerron

      i think you need to use Bitmap and create a byte[] from Bitmap and then create the statement to store

  • nice tutorial @ravi8x:disqus sir! easy to understand!

    • SIR NAME İS MAHO

      SİİİR.. SİİİR RAVİİİİ.. SİR.. IIIH .. IMMMM SIRR

  • Join Kelly

    Why not support nexus 7 device ?

  • Nagginda Sumayyia

    May anyone help me please. i want to know how to submit both the image and the video captured from android device to mysql/PHP database.

  • Huỳnh Thanh Tuấn

    someone help me…how to call intent into ArrayAdapter…i have one gridview and once gridview_item have a image…i want when click into this image,it will call intent give them take a picture

  • Laureen Tan

    Thank you for the tutorial. But anyone know how I can retrieve all the images that is saved in folder after following the steps above from my phone?

  • Absar Hussain

    i copy paste that code .. no errors .. But this code is not working.. can anyone help me??

  • youming2007

    There are some code errors in this tutorial: (It takes me 2 hours to get around with them xD)

    1. When recording video, it will throw error after recording and saving recorded video to the location specified in MediaStore.EXTRA_OUTPUT, as mentioned here: http://stackoverflow.com/questions/12458318/nullpointerexception-at-com-sec-android-app-camera-camcorderengine-renametempfil. Solution is just remove that line and assign a value to fileUri = data.getData() in onActivityResult callback. The recorded video would be save in default location.

    2. Use videoPreview.setVideoURI(fileUri) instead of videoPreview.setVideoPath(fileUri.getPath) when working with the above workaround because data.getData() return a uri related to a media content provider instead of actual path.

    Anyway, it’s an awesome tutorial.

    • sanjay

      Thanks, same error i was also getting while saving the video file.

  • ah_trini

    good tutorial :)!

    It will also threw errors for the overidden “SetOnClickListener”methods for the buttons.

    Remove those two methods and add these for the respective button tagsin xml.
    android:onClick=”captureImage”

    android:onClick=”recordVideo”

    • ah_trini

      oh and change the method signatures to:
      public void captureImage(View view){}
      public void recordVideo(View view){}

  • sania12

    it s working fine but it s taking such a long time after capturing image

  • Naman Gupta

    Hey! The preview is not working in the app. The Image gets stored in the right directory, but after the camera closes, their is nothing to display on the app activity.

  • Damian Dennis

    nice one, best tutorial so far.

  • yamuna

    i import your source code but my application displaying force to close message

  • yamuna

    when i click take the photo button it waits 2sec and displays force to close an application message

  • mukesh

    Hey! can we do same for front facing camera ?

  • Mukesh Krishnan

    Thank you coder !!!! you are really awesome ……..love you

  • meghana

    nice tut…

  • prasad Vdv

    can display camera in layout within the app

  • Atul

    can anyone tell the code that will directly start video recording on button click….bcoz above code calls system camera and then we press button for recording(ie.takes 2 clicks….i want it in a single click)

  • Guest

    This code has not work in android 4.4.4 kit kat

  • Toqeer

    can we add textview during video recording

  • Vikas Goyal

    this code is not working

  • Akash Saviaram

    great tutorial.. thank you so much.!

  • Amadeus Prime

    Hi Guys, what if i want to capture multiple photos and display them in a listView or recyclerView instead of an imageView, any suggestions?

  • Khyati

    i get null pointer exception in getOutputMediaFileUri()

  • great work !!

  • thomas kerioh

    i love this.thanks for the great work but one question,what changes do i need to make if am using android studio?

    • Satish Rajput

      You can simply import the project in Android Studio. Studio detects itself whether the project created in eclipse. If so then Studio tries to configure as suitable for Android Studio Project.
      It can take some time showing message…gradle is building…

      If it still not working for you then you need to do….
      create a new application in android studio then just copy and paste entire code from old project’s MainActivity to new Project’s MainActivity. Also copy permissions in new Manifest file.

  • Abhijit Murgod

    sir, can i capture image by double or single clicking on any part of camera (not the inbuilt camera button in android mobile phone), when camera is open in the mobile…
    I have created an App for blind people, that must capture image (which contains text), if text is present App will convert image to voice.. blind can hear the voice.. but the problrem is they cannot see the image capture button in phone… please help me by sending the code for this problem.. problem statement : “if blind people clicks on any part of camera, the application should capture image”. please do help

  • chha

    working code.. great job. thank you

  • Stark

    Thanks for your post.
    I found error in
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    and MEDIA_TYPE_IMAGE too.
    I thought it is my real device don’t have external storage?

  • Saba Younis

    great work thanks

  • vishal singhal

    hello sir, i want to capture three images in one activity on clicking 3 camera icons and showing in three image views, but i want to upload these images on server but i got null in intent data in OnActivityResult. please help me

  • amutisya

    thanks a lot androidhive..

  • ANKITA

    we are getting MultiPartEntity deprecated
    What to do? Please help…its urgent

  • Gaurav Meghanathi

    how to store gallery images like 4 to 5mb in sqlite database.dynamic if any one can tell me…?

  • Sumeet Rathore

    what to do if i need to store capture image into specific folder not in gallery like i need to create folder and store that capture image. what changes i need to do in this same code. Anyone?

    • Sumeet Rathore

      @ravi8x:disqus sir can you please help me here?

  • Nidhin Kumar

    Hi i have used the above code and tried to capture image and it works fine but if i capture the image in some other devices like samsung the image gets rotated to 90 degrees for that what i have to do to avoid the rotation of images while capturing

  • Rajesh

    Nice and Working Code………Thank You…..

  • Venktesh Sakthi

    whats the value of RESULT_OK???

    • TimeTraveler

      if you are using Activity then its Activity.RESULT_OK ,if it is fragment then getactivity().RESULT_OK.

  • manivel.m

    great a working thanks

  • Bhanu Prakash

    what is the finish() method for?

    • chandan lal

      to exit from application.

  • Johnny

    This tutorial is great! I do want to ask: what would you need to change/add to make this work from a fragment?

    • varun

      i have same query

  • puntodamar

    the code is working. but I can’t find the pictures on my phone gallery.

  • TimeTraveler

    As always another great Tutorial from RAVI.. 🙂

  • md. saifuddin Khan

    hello ravi, I want to store the images in sequence naming like IMG_1,IMG_2… and so on.
    PLZ help me!!!

    • lowi adrian colinares

      File mediaFile;

      if (type == MEDIA_TYPE_IMAGE) {
      mediaFile = new File(mediaStorageDir.getPath() + File.separator
      + “IMG_” + 1 + “.jpg”);

      }

  • sanjay

    Hi Ravi, app crashes once you save the video and try to come back from camera activity. Can we close camera activity once we save the video file?

  • RiShi DeEp

    getOutputMediaFileUri(CameraActivity.java:249)
    captureImage(CameraActivity.java:110)
    access$000(CameraActivity.java:27)
    $1.onClick(CameraActivity.java:65)

    errors

  • Rahul

    how to manage image get rotate in android device

  • ancy

    how to get rectangle overlay on camera

  • Mr. Ben

    Hi Sir Ravi
    im Ben from Malaysia
    i need your help by your expert in android
    i cant solve that how to code an application by using android phone camera to scan the colors and display the colors name
    My project is want to help whose colors blindness people
    may i get your help ? or any advice ?
    wait your reply
    thx Sir

  • Krishna Ch

    how to delete the picture from the gallery with its folder after capturing the image and uploaded to server?

  • Teraiya Mayur

    is it Comptible with Android OS 7.0 ?

  • sawdroiddev

    Null Pointer Exception:-
    public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
    }

  • Sunche Khan

    Great totarial Ravi, works fine. But this Camera API(android.hardware.camera) has deprecated. Am kindly looking for a way to implement both camera’s APIs (android.hardware.camera and android.hardware.camera2) to support older and higher android versions. Any help will be helpful. Thank you

  • shweta

    🙁 using this code i got exception in android version 6.0

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.news.cinepolis, PID: 9397
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:452)
    at com.news.cinepolis.MainActivity.getOutputMediaFileUri(MainActivity.java:243)
    at com.news.cinepolis.MainActivity.captureImage(MainActivity.java:104)
    at com.news.cinepolis.MainActivity.access$000(MainActivity.java:23)
    at com.news.cinepolis.MainActivity$1.onClick(MainActivity.java:58)

    • hafizh

      yeah..same with me, i got error on creating directory… have you solve that problem?

      (edited)..
      i add this additional request permission then calling it from onCreate and it works

      private void requestRuntimePermission() {
      if (Build.VERSION.SDK_INT >= 23) {
      if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
      != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this,
      new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
      }
      }
      }

      • shweta

        exactly in marshmellow we need to provide additional permission in manifest as well as in our java class . i also use runtime permission in java class in onstart().
        this is my method.

        public void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
        }

        //And finally ask for the permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
        }

        //This method will be called when the user will tap on allow or deny
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        //Checking the request code of our request
        if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        // if(userChoosenTask.equals(“Choose from Library”))
        // galleryIntent();
        } else {
        //Displaying another toast if permission is not granted
        Toast.makeText(this, “Oops you just denied the permission”, Toast.LENGTH_LONG).show();
        }
        }
        }

  • Ronel Gonzales

    thanks

  • lowi adrian colinares

    Hey Mr. Ravi, your codes was very helpful and i would like to say thank you for sharing it to us, but i’ll only have one question, can you add some functions on how to scaled the image or lessen the file size or simply reduce the size of image before it save??? please do response, your response will be a big help not to me but also for them.

    • The image is already compressed in previewCapturedImage() function. Check the below link to see how to reduce the dimensions
      https://stackoverflow.com/questions/15759195/reduce-size-of-bitmap-to-some-specified-pixel-in-android

      • lowi adrian colinares

        Again Mr. Ravi, thanks for your great response, you’re so amazing, I believe that the higher InSampleSize value will reduce the dimension of the image, and I used it but the preview image display small size in the screen and still the file size of the image was big, and regarding to the link that you said, how to apply the method of reducing image size in your code? particularly on or before saving??? please do response again Mr Ravi. Thank you so much!!!

        • Alifia Choirunnisa

          hai adrian, i have same problem with you, have you solved it?

          • lowi adrian colinares

            Hi Alifia, I already solve it by creating a method that will scale down the actual size of image or simply reduce the actual file size of image before saving it to my phone storage. i used the method from the given link of Mr. Ravi but I also create a Save method and called the Scale Down method to use it and it will works.

          • Alifia Choirunnisa

            thanks adrian it’s work, I create a save method to save a small size and delete the big size file.
            I wan’t to ask again, from this tutorial we save file with custom name as we want, but can we save it with the real name of photo? @ravi8x:disqus @lowiadriancolinares:disqus

          • lowi adrian colinares

            its good to hear that you made the saving of scales size image 🙂 .

            yes, we save a custom filename as we want, but i believe that the real name of image was customised, so why would you like to get the real image name if you can make your own image name ???

          • Alifia Choirunnisa

            I use gps map camera application to get gps coordinate too from image metadata, but I don’t know how to get image metadata from android, so I want to get the gps coordinate from the real name. hehe 🙂
            But now it can solved with another way, I get the image metadata by exif in php code 🙂

          • lowi adrian colinares

            nice nice good job 🙂

    • Ogbonda Glory

      try compressing the image sent with this method

    • Ogbonda Glory

      private String decodeFile(String path, int DESIREDWIDTH, int DESIREDHEIGHT)
      {
      String strMyImagePath = null;
      Bitmap scaledBitmap = null;
      try {
      Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
      if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
      scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
      } else {
      unscaledBitmap.recycle();
      return path;
      }
      String extr = Environment.getExternalStorageDirectory().toString();
      File mFolder = new File(extr + "/TMMFOLDER");
      if (!mFolder.exists()) {
      mFolder.mkdir();
      }
      String filename= newString.substring(newString.lastIndexOf("/")+1);
      String s = filename;
      File f = new File(mFolder.getAbsolutePath(), s);
      strMyImagePath = f.getAbsolutePath();
      FileOutputStream fos = null;
      try {
      fos = new FileOutputStream(f);
      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
      fos.flush();
      fos.close();
      } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (Exception e) {
      e.printStackTrace();
      }
      scaledBitmap.recycle();
      } catch (Throwable e) {
      }
      if (strMyImagePath == null) {
      return path;
      }
      return strMyImagePath;
      }

    • Ogbonda Glory

      Then u can now call the method using ur imagePath

      imagePath= decodeFile(imagePath,400,400);

  • John Mann

    Hello Ravi, it’s very nice to have found this tutorial. Thanks.
    I took a photo using the compiled app but couldn’t find the photo file afterwards. It even didn’t show up among “Recents”. This is on a Samsung Galaxy Tab S2. I have an SD card installed. Can you help me out?

  • Edwin Gomez Ortega Callaú

    Good job, but if I want to save to internal storage what can I do?

  • Merve

    why photos look horizontally?how the photos always look vertical?

  • Mohd Qasim

    this code is giving exception in 6.0+ versions
    Failed to load module via V2: java.lang.ClassNotFoundException: Didn’t find class “com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader” on path: DexPathList[[zip file “/data/app/com.example.ccs.loginapp2-1/base.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_dependencies_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_0_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_1_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_2_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_3_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_4_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_5_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_6_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_7_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_8_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_9_apk.apk”],nativeLibraryDirectories=[/data/app/com.example.ccs.loginapp2-1/lib/x86, /system/lib, /vendor/lib]]

  • Maki

    It does not save the image or video =(

  • Arvind Koli

    Hello Sir Very Nice Tutorial It Helped All but I’m trying to run this code in My Mobile with no sd card then it was crashed……
    And Give Me This Message “Oops! Failed create Hello Camera directory” in Log cat
    wiht Error
    https://uploads.disquscdn.com/images/e48fc570bb12e4810aa5643caf8c0c2c2fdc7e4136750950b435f28be3743fca.jpg

  • Hasan Rahman Sawan

    Hi Ravi,
    Could you please help me with how to add a rectangular size overlay in the camera screen similar to the BarcodeScanner, I am trying to scan driving license. It would be really nice to create a rectangle shape while taking the picture and put shadow on the other parts. Thanks.

  • Sorry Alex 🙁 I couldn’t get your query clearly.

    • Alex Cohn

      Sorry for not being clear enough, I updated my request. Please let me know if I can help you more.

      • Thanks Alex for your valuable suggestion. I don’t know why I haven’t thought of this until now. Will follow this from next article.

        BTW: It should be id instead of name <a id=”11″ …/>

        • Alex Cohn

          My HTML happens to be rusty. Anchor tag with name was required long time ago. Now with HTML 5, you can simply add id to any h2 (or other element) and hash references will work. You can probably do this with CSS, but this may interfere with your Web publishing platform.

          • Yup, I’ll see how easily it can be done 🙂

  • Sanket Solanke

    what if i want to display that image in another activity….

    • You just have to send the stored path of the image to another activity. On the other activity use the same path and display the image.

  • md. saifuddin Khan

    Hello Ravi,
    How to add timestamp on image when captured using camera. I have used your android-working-with-camera-api.

    Please help me …

  • Sourabh Wasnik

    first error, nullpointerexception
    second error,fileuriexposedexception
    and a permission issue as well.
    after spending 3-4 hours and trying other methods, I couldn’t find any efficient solution
    Im using android 7.0, can you please provide error free and updated code.

  • Ayush Mahajan

    Sir how can we see all the images which we captured and videos which we recorded in our Fragment?

  • Robson C

    Hello Ravi, thanks for the content, it helped me a lot.

    I have a problem in android Kitkat (Api 19) and I realize that at the time of creating the folder there is an error, the folder that should be created on the SD Card is created in the Internal Storage and therefore an error occurs because the directory does not exist
    new File (mediaStorageDir.getPath () + File.separator

    The same apk in Lollipop works very well, is there anything to be done to solve the problem on Kitkat?
    Thank you

    • Hi Robson

      Earlier it was on SD card only. Then I have changed the article. You can write a condition to check the version and choose proper storage location.

      • Robson C

        Hi Ravi, Thank you
        Obrigado!!!

  • Boopathi

    Hi Sir, Your code is working ,thank you very much.

    I want post to this image and additional text in server .

    Please Help me sir.

    Thank you

  • Raju Shingadiya

    you are awssom

  • derangula varuntej

    how to get bus details and book bus ticket details from server like redbus app and send booking details to customer.could you please help me or write article on this