Right now I've got an app that takes a photo via an intent. After taking the photo, I want the user to be able to confirm it and push the photo to another activity where they can add details. I'm struggling to find the correct way to pass the photo from activity to activity.
Right now, confirming the photo brings the user back to the main activity.
Here's my relevant code:
Main Activity
public void takePhoto(View view) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("MySecondApp",fileUri.toString());// create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data!=null) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MySecondApp");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MySecondApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
I would try something like
if(resultCode == Activity.RESULT_OK)
handleCameraPhoto(data);
handle method:
private void handleCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", mImageBitmap);
startActivity(intent);
}
and then, retrieve it in your other activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
and assign it to your ImageView
ImageView iv = (ImageView)findViewById(R.id.myImageView);
iv.setImageBitmap(bitmap);
Make a constructor in your new class that takes an intent or even the image:
class newClass {
public newClass(Intent intent){
...
}
...
}
And then just make the intent the size of a thumbnail in this new class where you can do the confirmation in a popup or something similar and then have the information to be filled on the page for this class. This will also be better because if they wanted to retake the picture you could have this class which they are taken to after the picture is taken if not accepted go to take another picture.
Take a look at this blog post I wrote on how to take a full size image and a thumbnail version as well:
Use Camera Activity for Thumbnail and Full Size Image
after you did that you can extract the file path of the saved file from the file instance using getAbsolutePath() method and pass it to the following Activity.
Related
I'm trying to get image from the camera or the gallery (whatever the user chose) in one intent. the problem is that I always get intent.getData() as null in OnActivityResult.
I'm doing the following as suggested here:
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });
startActivityForResult(chooserIntent, SELECT_PICTURE);
OnActivityResult:
if (requestCode == SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
final Uri imageUri = data.getData();
Log.e("uri", imageUri + "");
uri is null
Well, ACTION_IMAGE_CAPTURE does not return Uri.
But if by any chance you really want to get the Uri after taking a photo by using it, then you need to specify the path for the picture (it will save the photo on that path, so it's not temporary).
This is one of that example (this will create directory & prepare the new file for your image):
// Determine Uri of camera image to save.
File root = new File(
Environment.getExternalStorageDirectory() + File.separator + locationName + File.separator);
root.mkdirs();
String fname = imagePrefixName + System.currentTimeMillis() + ".jpg";
File imageMainDirectory = new File(root, fname);
Uri outputFileUri = Uri.fromFile(imageMainDirectory); //make sure you store this in the place that can be accessed from your onActivityResult
After you decided your outputUri & store it, then you need to implement that uri on your camera intent like this:
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
Then, when you received the data you can do this to check if the picture is come from gallery or camera (picture that stored has Uri on it):
final Uri imageUri = data.getData();
if (imageUri == null)
{
imageUri = outputFileUri;
}
Make sure you implement the permission for write & read external storage & with this, i think you will get Uri that you want.
I am trying to capture an image and then display it on the screen using another activity. I am able to successfully capture the images and save them in my desired directory. However, even after hours of struggle, I am still unable to solve this problem. The touch listener is added to the screen though there's no image.
Here's the code:
private void takeImage(){ Intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, PHOTO_TAKEN); }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_TAKEN){
data.putExtra(SET_CAPTURED_IMAGE, true);
} else{
Log.d(MainActivity.DEBUGTAG, "Photo = null");
}
}
Now in another activity (ImageActivity):
addTouchListener() is called in onCreate() method of this activity.
Till here, the image is successfully captured and saved in the directory.
private void addTouchListener(){
ImageView imageView = (ImageView)findViewById(R.id.unlocker_image);
Bundle extras = getIntent().getExtras();
//The following if block is not executed
if (extras != null && extras.getBoolean(MainActivity.SET_CAPTURED_IMAGE)){
Uri imageUri= Uri.parse(extras.getString(MediaStore.EXTRA_OUTPUT));
imageView.setImageURI(imageUri);
} else {
imageView.setImageResource(R.drawable.unlocker_image);
//this is the default image added
}
imageView.setOnTouchListener(collector);
}
At this point, the touch listener is added but there's no image.
I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path
I am making an app that will let users take photos and save them to the app, which will be password protected. So far, the app can take a picture, retrieve it, and set it to an image view. However, when I restart the app the image goes away. How can I save it?
int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
Uri imageUri;
public void takePic(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "filename_" +
String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra("data", imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Bundle extras = data.getExtras();
Log.e("URI", imageUri.toString());
Bitmap bmp = (Bitmap) extras.get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bmp);
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}
That imageUri you pass to the Intent- the image file is saved there. Just save the URI in SharedPreferences or other persistant storage and check that storage next time you launch your app.
This code is working on me :
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
This is how to define mFileTemp
String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
Your global variables
private Uri mImageCaptureUri;
private File mFileTemp;
1) Define your global variables
2) Then define mFileTemp
3)Then trigger takePicture() method
What i wanna do is simply add log line with file name which was recently captured. Unfortunately, application fails because of below indicated error. Code and error from stack provided below.
Thanks in advance,
Anar
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=100, result=-1, data=null} to activity
{az.justx.justx/az.justx.justx.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.net.Uri android.content.Intent.getData()' on a null object
reference
private void interceptCameraButtonClick() {
Button cameraButton = (Button) findViewById(R.id.cam);
cameraButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File image = new File(imagesFolder, "AD_" + timeStamp + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 100);
}
}
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Test", Integer.toString(resultCode));
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.i("CALLED", "Image saved to:\n" +
data.getData());
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
There is no requirement that the camera send back the Uri in the Intent delivered to onActivityResult(). You already know what the Uri is, as you put it in EXTRA_OUTPUT. You just need to use that value. Be sure to include it in your saved instance state, as your process may be terminated while the camera app is in the foreground.