3

enter image description hereThe first activity has a button which when clicked, opens the inbuilt camera. Now when the picture is taken, a new activity opens with the image captured in an imageView and a share button in the next activity. I have set up the activity to open after the image is taken, however I am unable to transfer image captured across activities. Please i need help or a nudge in the right direction.

The first activity which takes the picture is Takepicture.java:

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import java.io.File;
import java.util.Date;

public class TakePicture extends Activity {
Button camerabutton;
Intent intent;
int requestCode;
int resultCode;
static int REQUEST_IMAGE_CAPTURE = 1;
SharedPreferences imagepreferences;
SharedPreferences.Editor imageeditor;
private String imgPath;
Uri setImageUri;
File file;
Uri imgUri;
public String getImagePath;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.takepicture);
    camerabutton = (Button) findViewById(R.id.button6);
    imagepreferences=getSharedPreferences("image", MODE_PRIVATE);
    imageeditor=imagepreferences.edit();
    camerabutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null)
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        startActivity(new Intent(TakePicture.this, Aftertakepicture.class));
    }
}
}

the second activity, Aftertakepicture.java:

package com.example.kesandunwokolo.febclasstest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

public class Aftertakepicture extends Activity {
Button camerabutton;
ImageView saveimage;
Button sharebutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aftertakepicture);
    camerabutton=(Button)findViewById(R.id.button6);
    saveimage=(ImageView)findViewById(R.id.imageView2);
    sharebutton=(Button)findViewById(R.id.button7);
}
}

The takepicture.xml for the first activity:

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take Picture"
    android:id="@+id/button6" />

The aftertakepicture.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_vertical">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Take Picture"
        android:id="@+id/button6" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView2"
        android:minHeight="100dp"
        android:minWidth="100dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Share"
        android:id="@+id/button7" />
</LinearLayout>

please any help would be appreciated!

Aria
  • 389
  • 3
  • 7
  • 25
  • 1
    How about passing in the image path of the captured image? – MetaSnarf Aug 21 '15 at 02:57
  • You can try this `if (resultCode == RESULT_OK) { if (mFileUri != null) { mFilePath = mFileUri.toString(); ... intent.putExtra("filepath", mFilePath); startActivity(intent); ... } }` – BNK Aug 21 '15 at 03:01
  • would this be under onCreate or onAcivityResult? – Aria Aug 21 '15 at 03:15
  • it did nothing, it just returned the first activity, with no image – Aria Aug 21 '15 at 03:30
  • You need `Intent intent = new Intent(mContext, SecondActivity.class);` I have tested. Moreover, in SecondActivity, you should process `Intent intent = getIntent(); String filepath = intent.getStringExtra("filepath");` at onCreate – BNK Aug 21 '15 at 03:58
  • the pic does not show up on my image view. – Aria Aug 21 '15 at 04:13
  • @BNK ill edit my question so you see what i have now – Aria Aug 21 '15 at 04:15

3 Answers3

1

Here are my solution, I have tested in my environment. Hope this helps!

If using emulator to test, make sure camera supported like this

enter image description here

UPDATE WIH FULL SOURCE CODE (NEW PROJECT):

MainActivity.java:

package com.example.photocapture;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;

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

public class MainActivity extends Activity {

    private Uri mFileUri;
    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        mFileUri = getOutputMediaFileUri(1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

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

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

        if (resultCode == RESULT_OK) {
            if (mFileUri != null) {
                String mFilePath = mFileUri.toString();
                if (mFilePath != null) {
                    Intent intent = new Intent(mContext, SecondActivity.class);
                    intent.putExtra("filepath", mFilePath);
                    startActivity(intent);
                }
            }
        }               
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    // Return image / video
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) { // image
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == 2) { // video
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}

SecondActivity.java:

package com.example.photocapture;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import java.io.File;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent intent = getIntent();
        String filepath = intent.getStringExtra("filepath");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
        filepath = filepath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
        File imgFile = new File(filepath);
        if (imgFile.exists()) {
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
            imageView.setImageBitmap(bitmap);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

activity_second.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.photocapture.SecondActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.photocapture" >

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/title_activity_second" >
        </activity>
    </application>

</manifest>

END OF NEW PROJECT

------------------

FirstActivity:

    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_first);

       buttonCapturePicture.setOnClickListener(new View.OnClickListener() {

           @Override
           public void onClick(View v) {                   
               captureImage();
           }
        });
    }

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

        if (resultCode == RESULT_OK) {
            if (mFileUri != null) {
                mFilePath = mFileUri.toString();
                if (mFilePath != null) {                    
                    Intent intent = new Intent(mContext, SecondActivity.class);
                    intent.putExtra("filepath", mFilePath);
                    startActivity(intent);
                }
            }
        }

        // refresh phone's folder content
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }

    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        mFileUri = getOutputMediaFileUri(1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

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


    private Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    private static File getOutputMediaFile(int type) {
        // External sdcard location
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == 2) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

SecondActivity:

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

        super.addContentView(R.layout.activity_second);

        Intent intent = getIntent();
        mFilePath = intent.getStringExtra("filepath");
        previewMedia();
        ...
    }

    private void previewMedia() {              
            BitmapFactory.Options options = new BitmapFactory.Options();            
            options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
            mFilePath = mFilePath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
            File imgFile = new File(mFilePath);
            if (imgFile.exists()) {
                final Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
                mImagePreview.setImageBitmap(bitmap);
            }
        }
BNK
  • 23,994
  • 8
  • 77
  • 87
  • for the new methods, do i put them before or after the onActivityResult() – Aria Aug 21 '15 at 04:34
  • Before or after? Both OK. Let me add button click code in FirstActivity for more clear – BNK Aug 21 '15 at 04:39
  • ok I've been able to make mine like yours, but am i to import "MEDIA_TYPE_IMAGE" and "MEDIA_TYPE_VIDEO" as anything, bc they both give errors so I can't run to see if it works – Aria Aug 21 '15 at 05:18
  • Error:(90, 32) error: cannot find symbol variable MEDIA_TYPE_VIDEO – Aria Aug 21 '15 at 05:24
  • Error:(88, 27) error: cannot find symbol variable MEDIA_TYPE_IMAGE – Aria Aug 21 '15 at 05:24
  • mFileUri = getOutputMediaFileUri(1); and return Uri.fromFile(getOutputMediaFile(type)); – Aria Aug 21 '15 at 05:55
  • Haizz, try my new source code (full project between BEGIN.. -- END...) – BNK Aug 21 '15 at 05:56
  • Show your logcat plz, or you should create new project and copy my code – BNK Aug 21 '15 at 06:10
  • i did just that and it wouldn't open the app, the emulator crashed. i have posted my logical – Aria Aug 21 '15 at 06:16
  • Ah, I think your emulator not supported camera. You can check by `private boolean isDeviceSupportCamera() { return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); }`. My app runs OK on real phone – BNK Aug 21 '15 at 06:20
  • my emulator supports camera, i don't think thats the problem. I tried the camera outside the app and it runs good. it has something to do with the two line of code i sent to you :/ – Aria Aug 21 '15 at 06:26
  • So, try add permissions into manifest file ` `. However, I think you should use real phone – BNK Aug 21 '15 at 06:29
  • 1
    omg IT WORKS! It was the permissions, I forgot to add that. THANK YOU SO MUCH. I am so grateful! – Aria Aug 21 '15 at 06:33
  • I added picture. With that, no permission needed – BNK Aug 21 '15 at 06:37
0

there are several ways to do accomplish this, via sending the bitmap itself within Intent (Not Recommended) or you save the image to the storage and send its path within the intent which is recommended. first you save the image to the SDCARD and then pass it within the intent for example

Intent intent = new Intent(this,MyClass.class);
Bundle bundle = new Bundle();
bundle.putString("IMAGE_PATH",imageFile);
intent.putExtras(bundle);
startActivity(intent);

and then in the other activity you could use

String path = getIntent().getExtras().getString("IMAGE_PATH");
Bitmap bmp = BitmapFactory.decodeFile(path);
myImage.setImageBitmap(bmp);
Kosh
  • 6,140
  • 3
  • 36
  • 67
  • the first part, do i add it under my onCreate or onActivityResult? – Aria Aug 21 '15 at 03:13
  • the first part you added after user click on a button or the image itself, rather than onCreate, the second part yes you do put it in onCreate in the other activity. if the answer is what you seek, please do accept it so people can benefit from it in the future. – Kosh Aug 21 '15 at 03:15
  • of course it will, 1- make sure you save the image first, 2- make sure you are passing the right path. 3- always check against null values. – Kosh Aug 21 '15 at 03:24
  • so how do i save it within the app? i do not want to retrieve from the phone's photo library – Aria Aug 21 '15 at 03:31
0

Refer to this link. You should save your image on a file and get the file path of that image. You can then pass the image path to the second activity.

Community
  • 1
  • 1
MetaSnarf
  • 5,857
  • 3
  • 25
  • 41