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?
Related
on capturing image from camera in lollipop and higher versions getting the result data null on onActivityResult.
launchCamera();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
((MyWebViewActivity) context).fileUri = CommonUtils.getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, ((MyWebViewActivity) context).fileUri);
((MyWebViewActivity) context).startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
#Override
onActivityResult(int requestCode, int resultCode, Intent data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if(fileUri!=null){
file_path = fileUri.getPath();
System.out.println("file-path---=" + file_path);
}else{
Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show();
}
if(!CommonUtils.isEmpty(file_path)){
}
} else if (resultCode == RESULT_CANCELED) {
// "User cancelled image capture",
} else {
// failed to capture image
}
}
getOutputMediaFileUri()
File file = getOutputMediaFile(type);
if (file != null) {
return Uri.fromFile(file);
}
return null;
getOutputMediaFile()
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "My Images");
// 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;
System.out.println("mediaStorageDir==" + mediaStorageDir);
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".png");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
It appears like you're starting the activity for result from a fragment. In that case you've to override the OnActivityResult() method in both the fragment and the Activity.
Check out this answer. This should help
https://stackoverflow.com/a/21826858/7659504
when I am using my native app camera to take video, the output file have 3gp extension. I need to intent to camera with ACTION_VIDEO_CAPTURE intent action which will produce a file that has a mp4 file extension. how can I do it?
You can go ahead and try dis code:
intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFile(MEDIA_TYPE_VIDEO); // create a file to save the video in specific folder (this works for video only)
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED_NEXUS);
This will be called once the capture is completed
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_VIDEO_CAPTURED_NEXUS:
this.videoFromCamera(resultCode, data);
break;
default:
break;
}
}
}
private void videoFromCamera(int resultCode, Intent data) {
if(fileUri != null) {
Log.d(TAG, "Video saved to:\n" + fileUri);
Log.d(TAG, "Video path:\n" + fileUri.getPath());
Log.d(TAG, "Video name:\n" + getName(fileUri));
// use uri.getLastPathSegment() if store in folder
//use the file Uri.
}
}
Get the output Media file uri with the following Method
public Uri getOutputMediaFile(int type)
{
// To be safe, you should check that the SDCard is mounted
if(Environment.getExternalStorageState() != null) {
// this works for Android 2.2 and above
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "SMW_VIDEO");
// 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(TAG, "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_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return Uri.fromFile(mediaFile);
}
return null;
}
This will save the captured video in pure MP4 format.
You can add the following code before start the intent :
videoUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fname_" + String.valueOf(System.currentTimeMillis()) + ".mp4"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
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.
Hi i started to use Camera in Android, as simple as it can get from here.
The problem is after i shoot the photo the file's uri is just null for some reason.
Steps:
I ran the takePhoto() func, my phone's standard camera app starts,
i take a photo, i save it.
My app ran the onActivityResult(...) func as it gets back the control from camera, and the file's uri is just null.
Code:
In my Activity:
/**
* Intent code for capturing a photo
*/
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
/**
*
* Takes a photo
*/
public void takePhoto() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = CameraHelper.getOutputMediaFileUri(CameraHelper.MEDIA_TYPE_IMAGE); // create a file to save the image
Log.i("PHOTO", "file uri is: " + fileUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
/**
*
* After taking the photo...
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
if (data == null) {
Toast.makeText(this, "Camera error: data is null!", Toast.LENGTH_LONG).show();
Log.i("PHOTO", "Camera error: data is null!");
// Error is here, data does not contains the uri.
}
else {
Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
Log.i("PHOTO", "Image saved to:\n" + data.getData());
}
}
else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
}
else {
// Image capture failed, advise user
}
}
}
CameraHelper class:
public class CameraHelper {
public static final int MEDIA_TYPE_IMAGE = 1;
/** Create a file Uri for saving an image or video */
public static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
// 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()) {
Log.i("PHOTO", "directory is not exists yet!");
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
else {
Log.i("PHOTO", "just made directory: " + mediaStorageDir.getAbsolutePath());
}
}
else {
Log.i("PHOTO", "directory is already exist: " + mediaStorageDir.getAbsolutePath());
}
// 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 {
return null;
}
return mediaFile;
}
}
Log output:
01-13 16:15:37.485: I/PHOTO(6818): directory is already exist: /storage/sdcard0/Pictures/MyCameraApp
01-13 16:15:37.495: I/PHOTO(6818): file uri is: file:///storage/sdcard0/Pictures/MyCameraApp/IMG_20150113_161537.jpg
01-13 16:16:13.482: I/PHOTO(6818): Camera error: data is null!
All the pictures are in the folder: Pictures/MyCameraApp but onActivityResult(...) does not contains the uri in the data field.
What m i doing wrong?
I am trying to save Video file on SD card but getting null pointer.
Have a look of my code.
I just need to create a folder in SD Card and save videos on it.
When i have not using fileUri then not got Crash.
File mediaFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/myvideo"+System.currentTimeMillis() +".mp4");
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, VIDEO_CAPTURE);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VIDEO_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(getActivity(), "Video has been saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getActivity(), "Video recording cancelled.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Failed to record video",
Toast.LENGTH_LONG).show();
}
}
}
Thanks.
Suggestion appreciated.
To Save File on SD Card Follow the code.
add "android.permission.WRITE_EXTERNAL_STORAGE" in manifest file."
And then use the code -
filePath = getExternalFilesDirs("/")[1].toString();
OutputStreamWriter writer;
File file;
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
file = new File(filePath + "yourfilename.txt");
writer = new OutputStreamWriter(ostream, "UTF-8");
//save your video file here
writer.close();
Try this,
private static File getOutputMediaFile(int type){
// Check that the SDCard is mounted
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraVideo");
// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
output.setText("Failed to create directory MyCameraVideo.");
Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
Toast.LENGTH_LONG).show();
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
Refer this link,
http://androidexample.com/Camera_Video_Capture_And_Save_On_SDCard_-_Android_Example/index.php?view=article_discription&aid=123
I wish it will help you.