onActivityResult resultCode always 0 when using camera - android

So i have 2 Activities, the first one is to launch camera before the second Activity start. After taking the camera, the ImageView on second Activities will changed by the photo ive taken. And if i click the ImageView, it will intent the camera and replacing the image from camera. However, i cant replace the image at ImageView and the resultCode always 0 everytime after taking picture.
here is first Activity
#OnClick(R.id.fab_toko)
private void create_ticket() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
//return FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName(), getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
//Creating an internal dir;
File mDir = RumahkeduaApplication.getContext().getDir("ISS", Context.MODE_PRIVATE);
//Internal Storage
// File mediaInternalDir = new File(mDir,Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaInternalDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaInternalDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Intent mainIntent = new Intent(MainActivity.this, CreateTicketActivity.class);
mainIntent.putExtra("id_user", login_user.getId_user());
mainIntent.putExtra("string_uri", fileUri.toString());
mainIntent.putExtra("ticket_type", "Toko Prima");
MainActivity.this.startActivity(mainIntent);
} 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();
}
}
}
And here is second Activity
#OnClick(R.id.iv_post_photo)
private void captureImage() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
// if (!ticket_type.equals("Toko Prima")){
// TODO
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
// start the image capture Intent
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
setResult(RESULT_OK);
// }
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Picasso.with(this).load(fileUri).fit().centerCrop().into(ivPhoto);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture0
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();
}
}
storage permission already checked on manifest

i used a combination of answers to make it work so i ended up with this code:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date dat = Calendar.getInstance().getTime();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");
String nameFoto = simpleDate.format(dat) + ".png";
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ File.separator +nameFoto;
File ff = new File(filename);
try {
ff.createNewFile();
//imageUri = Uri.fromFile(ff);
imageUri = FileProvider.getUriForFile(IngresarFactura.this, BuildConfig.APPLICATION_ID + ".provider",ff);
//imageUri = new Uri(filename).
if (imageUri.getPath() == null){
mensaje.setText(filename+ " Error path es nulo.");
}
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
//COMPATIBILITY
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) {
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = IngresarFactura.this.getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
IngresarFactura.this.grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
//COMPATIBILITY
activityResultLaunch.launch(cameraIntent);
}
you also have to do this as answered here:
https://stackoverflow.com/a/45751453/16645882

Related

Record a video and save in SD card

I take a photo and save it to external storage :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = getPhotoFile();
String authorities = getActivity().getPackageName() + ".fileprovider";
imageUri = FileProvider.getUriForFile(getActivity(), authorities, photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1);
It works fine
But what about recording a video
I wrote some code like this but i think it's not correct :
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File videoFile = getVideoFile();
String authorities = getActivity().getPackageName() + ".fileprovider";
videoUri = FileProvider.getUriForFile(getActivity(), authorities, videoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(intent, 2);
What can i do?
EDIT:
And these methods create a dir and return photo and video files
public File getPhotoFile() {
//create a random name
String randomName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File mainPath = new File(path, "/Images");
if (!mainPath.exists()) {
mainPath.mkdirs();
}
File photoPath = new File(mainPath, randomName + ".jpg");
return photoPath;
}
public File getVideoFile() {
//create a random name
String randomName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File mainPath = new File(path, "/Videos");
if (!mainPath.exists()) {
mainPath.mkdirs();
}
File photoPath = new File(mainPath, randomName + ".mp4");
return photoPath;
}
To record video use:
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
Here is an example
in your recordVideo.onClick() method add this code
if (checkPermissions(YourActivity.this)) {
captureVideo();
} else {
requestCameraPermission(MEDIA_TYPE_VIDEO);
}
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;
}
//in CaptureVideo method
private void captureVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File file = getOutputMediaFile(MEDIA_TYPE_VIDEO);
if (file != null) {
imageStoragePath = file.getAbsolutePath();
}
Uri fileUri = 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);
}
/**
* 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),
YourActivity.GALLERY_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e(YourActivity.GALLERY_DIRECTORY_NAME, "Oops! Failed create "
+ YourActivity.GALLERY_DIRECTORY_NAME + " directory");
return null;
}
}
public static Uri getOutputMediaFileUri(Context context, File file) {
return FileProvider.getUriForFile(YourActivity.this, context.getPackageName() +
".provider", file);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Refreshing the gallery
refreshGallery(getApplicationContext(), imageStoragePath);
// video successfully recorded
showVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
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) {
}
});
}
private void showVideo() {
try {
videoView.setVideoPath(imageStoragePath);
// video playing
videoView.start();
} catch (Exception e) {
e.printStackTrace();
}
}

How to display capture image from camera and display in imageview from file path? [duplicate]

This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 6 years ago.
My problem after taking a photo and then createImageFile .. onActivityResult, photo does not appear on img_photo. how to make appear in img_photo ?
img_photo = (ImageView) findViewById(R.id.imgPhoto);
// take a photo from camera
imgBtnCamera = (ImageButton) findViewById(R.id.imgBtnCamera);
imgBtnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(PhotoSubmitActivity.this,
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Create image file
// Create image file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
Log.v("This is totally working", "Yeah!");
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
img_photo.setScaleType(ImageView.ScaleType.CENTER_CROP);
img_photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I attended training on this link Taking Photos Simply
i had same problem too.but i solved it.
#Driyanto Saputro see in my code where i placed a comment for save Captured image in ImageView.
also Note : i am working on Custom Camera not Using Existing Camera.
i paste my code below to Save Captured image in imageView.
public void CaptureImage() {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
// Convert byte array into bitmap
final Bitmap originalBitmap = MainActivity.decodeSampledBitmapFromByte(getApplicationContext(), data);
// Rotate Image
Matrix rotateMatrix = new Matrix();
final Bitmap rotatedBitmap;
if (mCameraId == CAMERA_FACING_FRONT) {
rotateMatrix.postRotate(270);
} else {
rotateMatrix.postRotate(90);
}
rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), rotateMatrix, false);
final File imageFolder;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
} else {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
}
boolean success = true;
if (!imageFolder.exists()) {
success = imageFolder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(imageFolder.getAbsolutePath() + File.separator + getFileNameCustomFormat() + " " + "Image.jpg");
SavedImagePath = getFileNameCustomFormat() + " " + "Image.jpg";
// imageFile.createNewFile();
} else {
Toast.makeText(getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Save image into gallery
if (rotatedBitmap != null) {
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
FileOutputStream file_out = new FileOutputStream(imageFile);
file_out.write(outputStream.toByteArray());
file_out.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(getApplicationContext(), "Photo Captured", Toast.LENGTH_SHORT).show();
// Code For Captured Image Save in a ImageView.
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
String imagePath = imageFolder.getAbsolutePath() + File.separator + SavedImagePath;
Uri myURI = Uri.parse(imagePath);
imgBtnThumbnail.setImageURI(myURI);
Toast.makeText(getApplicationContext(), "Photo Saved on ImageView", Toast.LENGTH_SHORT).show();
}
});
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I hope it will help You.(:
Try this way it will help
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving 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) {
// 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) {
// 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 a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new 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;
}
}
http://www.androidhive.info/2013/09/android-working-with-camera-api/

Trying to take a picture and then store it + have access to it

So, I have an app where I want to take a picture, store it to internal storage, and then be able to retrieve it later (presumably via its Uri). Here is what I have thus far:
This code is triggered when my custom camera button is pressed.
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = herp(MEDIA_TYPE_IMAGE);
if (file != null) {
fileUri = getOutputMediaFileUri(file);
Log.d("AddRecipeActivity", fileUri.toString());
takePic.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePic, CAMERA_REQUEST);
}
}
});
Next, I've defined two methods later on in the code(mostly taken from the android developer site):
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(File file){
return Uri.fromFile(file);
}
/** Create a File for saving an image or video */
public File herp(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
Boolean a = false;
String externalDirectory= getFilesDir().getAbsolutePath();
File folder= new File(externalDirectory + "/NewFolder");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!folder.exists()){
a = folder.mkdirs();
Log.d("AddRecipeActivity", String.valueOf(a));
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(folder.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
if(mediaFile == null){
Log.d("AddRecipeActivity", "Media file is null");
}
return mediaFile;
}
When I print my Uri (right before triggering the intent) I get the following output.
04-04 04:22:40.757 22402-22402/scissorkick.com.project2 D/AddRecipeActivity: file:///data/user/0/scissorkick.com.project2/files/NewFolder/IMG_20160404_042240.jpg
Also, when I check if the directory is made, the boolean is true.
When my camera intent's onActivityResult is run, however, the result code is 0.
Why might it fail at this point? I've defined the appropriate permissions in the manifest, and also request external storage write permissions during run time.
Edit: Added the onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST){
Log.d("AddRecipe", String.valueOf(resultCode));
if(resultCode == RESULT_OK){
photo = (Bitmap) data.getExtras().get("data");
thumb = ThumbnailUtils.extractThumbnail(photo, 240, 240);
photoView.setImageBitmap(thumb);
//Toast.makeText(getApplicationContext(), "image saved to:\n" + data.getData(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();
}
}
}
There's some nonsense code in the onActivityResult, but the point is that the resultCode = 0 and I don't know why.
In your final activity, put the below code
data.putExtra("uri", uri);//uri = your image uri
getActivity().setResult(""result_code", data);
getActivity().finish();
Then in your onActivityResult code you can get the uri like
Uri uri = data.getExtras().getParcelable("uri");
Then you can use this Uri value to retrieve your image.
There is how i take picture in my app!
When i press my own Image Button
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1
static final String STATE_PHOTO_PATH = "photoPath";
ImageButton photoButton = (ImageButton) this.findViewById(R.id.take_picture_button);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
And here how manage and create/store the file with image
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
//Create a new empty file for the photo, and with intent call the camera
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
// Error occurred while creating the File
Log.e("Error creating File", String.valueOf(e.getMessage()));
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
//I have the file so now call the Camera
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private void openImageReader(String imagePath) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.parse(imagePath);
intent.setDataAndType(imgUri, "image/*");
startActivity(intent);
}
In the ActivityResult i only save a record in DB, with the Path of the image so i can retrieve it back and read the photo stored like file.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//Save the path of image in the DB
db.addCompito(new Compiti(activity_name, null, mCurrentPhotoPath));
refreshListView();
}
}
If you have some screen rotation don't forget to add something like
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(STATE_PHOTO_PATH, mCurrentPhotoPath);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentPhotoPath = savedInstanceState.getString(STATE_PHOTO_PATH);
}
WHY?
Because when the rotation change you can lose the file that you have created for the "new photo" and when you accept it and save it, your photopath is null and no image is created.

Android Camera OnActivityResult resets photo path to null

I'm having a problem while testing my app on a friends Galaxy S4 (GT i9505, Android 5.1). When giving a file URI to camera intent, OnActivityResult gives result Activity.RESULT_OK and and the path is null. It is working on most of other devices I tested (LG G3, nexus 5...). This is my code:
GetOutputMediaFile
public File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), MediaChooserConstants.folderName);
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MediaChooserConstants.MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} else if(type == MediaChooserConstants.MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
String picturePath = null;
if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
picturePath = fileUri.getPath(); // <--- fileURI is null
}
}
}
DispatchTakePhotoIntent
private void dispatchTakePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = Utils.getInstance().getOutputMediaFile(MediaChooserConstants.MEDIA_TYPE_IMAGE);
fileUri = Uri.fromFile(file); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
//fileUri is not null here while debugging (../DCIM/.../IMG_XXX.jpg)
startActivityForResult(intent, MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
you need to save the file path to the bundle in onSaveInstanceState and then get it again in onRestoreInstanceState from the bundle
Save path of image like this :
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
if(mImageCaptureUri!=null)
savedInstanceState.putString("camera_image", mImageCaptureUri.toString());
super.onSaveInstanceState(savedInstanceState);
}
And Retrieve image path from this :
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("camera_image")) {
mImageCaptureUri = Uri.parse(savedInstanceState.getString("camera_image"));
}
}
super.onRestoreInstanceState(savedInstanceState);
}
This problem happens, Only when user goes to camera intent and by the time he captures the image the activity on which camera intent was hosted gets destroyed or recreated when user comes back from the camera intent.

Android video capture intent crashes

I need to record a video within the application using the intent. I think the code is correct, however when I do start the image stops and the file gets 0Bytes. I let down the code I'm using.
The first function called:
protected void makeVideo() {
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
getOutputMediaFile function:
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
// Environment.getExternalStorageState();
// File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), Constants.ALBUM.AlbumInPhone);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), Constants.ALBUM.AlbumInPhone);
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d(Constants.ALBUM.AlbumInPhone, "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new 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;
}
File x = mediaFile;
int y=0;
y=1;
return mediaFile;
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
and:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
// Toast.makeText(this, "Video saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
String uri = fileUri.getPath();
if(TextUtils.isEmpty(uri)){
Log.v(TAG, "Could not get video");
} else {
Log.v(TAG, "video: " + uri);
if(BebeDataBaseManager.addVideoToAlbum(this, uri, albumId)){
Log.v(TAG, "video: added");
this.cursor.requery();
} else {
Log.v(TAG, "video: not added");
}
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
...
I'm doing something wrong?

Categories

Resources