Question

I am trying to take a picture and view it on the screen with the following code:

public class MainActivity extends ActionBarActivity {
    private static final int PICTURE_REQUEST_CODE = 100;
    public Button camera, gallery;
    private Uri fileUri;
    private static File mediaFile;
    ImageView image;
    public String fileName;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera = (Button) findViewById(R.id.button1);
        gallery = (Button) findViewById(R.id.button2);
        createListeners();
    }
    private static Uri getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Mustache");
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");

        return Uri.fromFile(mediaFile);
    }
    public void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFile(); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, PICTURE_REQUEST_CODE);

    }
    public void launchGallery(){
        Intent gallery = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        fileUri = getOutputMediaFile(); // create a file to save the image
        gallery.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(gallery, PICTURE_REQUEST_CODE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
               System.out.println(String.valueOf(requestCode));
               System.out.println(String.valueOf(resultCode));
               System.out.println(data);
               Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
               Uri contentUri = Uri.fromFile(mediaFile);
               mediaScanIntent.setData(contentUri);
               this.sendBroadcast(mediaScanIntent);

    }
    public static final int MEDIA_TYPE_VIDEO = 2;

    private void createListeners() {
        System.out.println("Started CreateListeners for Main Activity");
        camera.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchCamera();
            }

        });

        gallery.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchGallery();
            }
        });
    }


}

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context="com.example.mustache.MainActivity"
    tools:ignore="MergeRootFrame" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:text="@string/main_camera_button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:text="@string/main_gallery_button" />

</LinearLayout>

However, the app takes a photo and saves it to my gallery, but then returns to the main screen without doing anything. How do I make it display the photo?

Was it helpful?

Solution

The only problem is you are not displaying the captured image.

You need to add an ImageView in your Layout and set the captured image in onActivityResult

Change your onActivityResult like this

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri contentUri = Uri.fromFile(mediaFile);

    ImageView imageView = (ImageView)findViewById(R.id.imageView1);
    imageView.setImageURI(contentUri);
}

Also, add an ImageView in your layout

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_weight="1"/>

OTHER TIPS

Everything looks fine except one thing: you've just created ImageView object but with no reference. You should do some changes to your code like this:

Add ImageView to your xml layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context="com.example.mustache.MainActivity"
    tools:ignore="MergeRootFrame" >

  <Button .... />
   <Button .... />
  <ImageView
        android:id="@+id/imageview"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
   </LinearLayout>

And then make a reference to your Activity class:

public class MainActivity extends ActionBarActivity 
    {
        private static final int PICTURE_REQUEST_CODE = 100;
        public Button camera, gallery;
        ImageView image;
       .........
       ........
        protected void onCreate(Bundle savedInstanceState) {
            System.out.println("Started Main Activity");
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           image = (ImageView)findViewById(R.id.imageview);
         }

then to your onActivityResult

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
               super.onActivityResult(requestCode, resultCode, data);
                   System.out.println(String.valueOf(requestCode));
                   System.out.println(String.valueOf(resultCode));
                   System.out.println(data);
              if(resulCode == RESULT_OK && requestCode == PICTURE_REQUEST_CODE)
            {
                   Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                   Uri contentUri = Uri.fromFile(mediaFile); 

                    image.setImageUri(contentUri);//set uri of captured image to imageview
                   mediaScanIntent.setData(contentUri);
                   this.sendBroadcast(mediaScanIntent);

            }

        }

make sure you set different RequestCode for launching camera and for selecting image from gallery.

You need Imageview:

public class MainActivity extends ActionBarActivity {
    private static final int PICTURE_REQUEST_CODE = 100;
    public Button camera, gallery;
    private Uri fileUri;
    private static File mediaFile;
    ImageView image;
    public String fileName;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera = (Button) findViewById(R.id.button1);
        gallery = (Button) findViewById(R.id.button2);
        createListeners();
    }
    private static Uri getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Mustache");
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");

        return Uri.fromFile(mediaFile);
    }
    public void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFile(); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, PICTURE_REQUEST_CODE);

    }
    public void launchGallery(){
        Intent gallery = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        fileUri = getOutputMediaFile(); // create a file to save the image
        gallery.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(gallery, PICTURE_REQUEST_CODE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
               System.out.println(String.valueOf(requestCode));
               System.out.println(String.valueOf(resultCode));
               System.out.println(data);
               Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
               Uri contentUri = Uri.fromFile(mediaFile);
               mediaScanIntent.setData(contentUri);
               this.sendBroadcast(mediaScanIntent);

    }
    public static final int MEDIA_TYPE_VIDEO = 2;

    private void createListeners() {
        System.out.println("Started CreateListeners for Main Activity");
        camera.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchCamera();
            }

        });

        gallery.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchGallery();
            }
        });
    }


}

This is simple technique. You should use AlertDialog.Builder for this purpose to display 3 options like:

1) Take Picture from camera 2) Choose from gallery 3) Cancel

and then just follow the steps below

See code below for help...

    ImageView profile_img; //When you select image either from Gallery or take from Camera the code will set your selected image to this ImageView... 

    Context context;

    final CharSequence[] items = { "Take Picture from camera", "Choose from gallery", "Cancel" };

    private static final int REQUEST_CAMERA = 0;

    private static final int SELECT_IMAGE = 1;

    Bitmap bmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_xml_layout_name);

        context = YourActivityClass.this;

        profile_img = (ImageView) findViewById(R.id.profile_img);

        profile_img.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) 
    {
        int id = v.getId();

        switch (id) 
        {

        case R.id.profile_img:

            selectImage();

            break;
        }
    }

    private void selectImage()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);

        alert.setTitle("Choose Options...");

        alert.setItems(items, new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dialog, int position) 
            {
                if(items[position].equals("Take Picture from camera"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent, REQUEST_CAMERA);
                }
                else if(items[position].equals("Choose from gallery"))
                {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent, SELECT_IMAGE);
                }
                else if(items[position].equals("Cancel"))
                {
                    dialog.dismiss();
                }
            }
        });

        alert.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK)
        {
            if(requestCode == REQUEST_CAMERA)
            {               
                Uri uri = (Uri) data.getData();

                try 
                {
                    bmp = decodeUri(uri);

                    profile_img.setImageBitmap(bmp);
                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                }
            }
            else if(requestCode == SELECT_IMAGE)
            {
                Uri uri = data.getData();

                try 
                {
                    bmp = decodeUri(uri);

                    profile_img.setImageBitmap(bmp);
                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                }


            }
        }
    }

    public String getPath(Uri uri) 
    {
        String[] projection = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException 
    {
        BitmapFactory.Options o = new BitmapFactory.Options();

        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 70;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;

        int scale = 1;

        while (true) 
        {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) 
            {
                break;
            }
            width_tmp /= 2;

            height_tmp /= 2;

            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();

        o2.inSampleSize = scale;

        return BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o2);
    }

Hope this will help you...Good Luck

// try this way,hope this will help you...

**XML** code

**activity_main**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_launcher"/>
    </LinearLayout>
    <Button
        android:id="@+id/btnCamera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Camera" />

    <Button
        android:id="@+id/btnGallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Gallery" />

</LinearLayout>

**ACTIVITY** code

**MainActivity**
public class MainActivity extends Activity {

    final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;

    private Button btnCamera;
    private Button btnGallery;
    private ImageView imageView;
    private String imgPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCamera = (Button) findViewById(R.id.btnCamera);
        btnGallery = (Button) findViewById(R.id.btnGallery);
        imageView = (ImageView) findViewById(R.id.imageView);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            }
        });

        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
            }
        });
    }

    public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }

    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = managedQuery(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);

            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAPTURE_IMAGE) {
                imageView.setImageBitmap(BitmapFactory.decodeFile(getImagePath()));
            } else if (requestCode == PICK_IMAGE) {
                imageView.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
            }
        }

    }

}

Note : add this permission on you "AndroidManifest.xml"
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top