Video recording using Intent saves empty file - android

This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks

String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}

first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}

Related

How to capture video from camera intent?

I want capture video from camera Intent and save in app directory (don't save video in Device Gallery) and insert video path into database to load and display in my app
i try in my activity :
public class VideoActivity extends Activity {
private TblVideo TBL_VIDEO;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
long date = System.currentTimeMillis();
String string_path = DATABASE_LOCATION + LAST_MOMENT_ID + "_" + date + ".mp4";
File mediaFile = new File(string_path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Button buttonRecording = (Button) findViewById(R.id.photo_btn_take_video);
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
fileUri = Uri.fromFile(mediaFile);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private String SaveMediaFile(int type) {
if (type == MEDIA_TYPE_VIDEO) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mediaFile);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string_path;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
try {
if (resultCode == RESULT_OK) {
insertVideo();
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
but when go to file directory , video size is 0Kb !! and save into device gallery
How to fix this problem ?
thanks
and try this but app is crash :
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
FileOutputStream fileOutputStream = null;
try {
FileInputStream fileInputStream = new FileInputStream(fileUri.getPath());
fileOutputStream = new FileOutputStream(mediaFile);
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
insertVideo();
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
}
}
i use this and save video file after activity result is OK, save video in directory !
private String SaveMediaFile() {
try {
InputStream in = getContentResolver().openInputStream(fileUri); // Uri
OutputStream out = new FileOutputStream(mediaFile); // file
byte[] buf = new byte[1024];
int len;
assert in != null;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو");
}
return string_path;
}
thanks

Save image in specific folder in android device

In my app, i can take a picture and save in gallery(folder 'camera').But i need save it in a specific folder in external memory.This is my code.How i can do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_pic);
init();
getPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle ex = data.getExtras();
bitmap = (Bitmap) ex.get("data");
myPic.setImageBitmap(bitmap);
}
}
This should do it:
private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Android: How to pass uri from onActivity result to another method?

How do i pass an uri from the onActivity result to another method in the same jave file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
method savevideo:
public void savevideo() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
}
I would like like pass the mVideoURI to savevideo method and then save the video uri into gallery. Can someone help me with this. Any guidance/suggestion would be really helpful. Thank you.
EDITED: FULL CODING:
public class AndroidVideoPlayer extends Activity {
Button button;
VideoView videoView;
private static final int PICK_FROM_GALLERY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_video_player);
button = (Button) findViewById(R.id.button);
videoView = (VideoView) findViewById(R.id.videoview);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
savevideo(mVideoURI);
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
public void savevideo(Uri mVideoURI) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
boolean success=false;
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
}
}
As per my understanding from your question, you have to call a method after getting a result from another activity. so you might be called startActivitForResult(activityB) for getting the video Uri. so you will get a callback from the activityB, thus you can directly pass the video to the method saveVideo() since it is in the same Activity.
Example
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
saveVideo(videoUri);
}
}
public void saveVideo(Uri videoUri){
// do operations with uri
}
or if you can't accept any arguments in saveVideo() method you can make uri as a member variable and use inside() method
use this code-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
saveVideo(mVideoURI); // methode to save uri gets called here
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
method savevideo:
public void savevideo(Uri mVideoURI) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
}
In your code, you are only creating new file on your destination path but not write the data of source file to destination file.
So you are getting 0KB file. Use the below code code for writing a file.
void savefile(URI sourceuri)
{
String sourceFilename= sourceuri.getPath();
String destinationFilename = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"abc.mp3";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
}

Android name image programmatically

I want to give a custom name to the image captured through the camera programmatically. I have used the snippets of codes given here how to control/save images took with android camera programmatically? but it still doesn't work and the image is stored with the default name. Why?
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cameraButton = (Button) findViewById(R.id.takepicture);
cameraButton.setOnClickListener( new OnClickListener(){
public void onClick(View v ){
//Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//startActivityForResult(intent,0);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_"+ String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
startActivityForResult(intent,0);
}
});
}
}
You can try as follows...
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String fullPath = "";
File imageFile = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String pictureName = "IMG_" + timeStamp + ".jpg";
fullPath = Environment.getExternalStorageDirectory() + "/ImageFolder/" + pictureName;
File dir = new File(Environment.getExternalStorageDirectory() + "/ImageFolder/");
dir.mkdirs();
imageFile = new File(fullPath);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
startActivityForResult(takePictureIntent, 1);
Try this: Here I saved image with current date and time as name:
public class CameraActivity extends Activity {
private static final int CAMERA_REQUEST = 0;
static Uri capturedImageUri=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_junit_test);
Button cameraButton = (Button) findViewById(R.id.cameraButton);
cameraButton.setOnClickListener( new OnClickListener(){
private int CAMERA_RESULT;
public void onClick(View v ){
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(), (cal.getTimeInMillis()+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, CAMERA_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
//Bitmap photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap( getApplicationContext().getContentResolver(), capturedImageUri);
//imageView.setImageBitmap(bitmap);
Toast.makeText(this, "Image Saved As"+bitmap, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Try This
public void CapturePhoto()
{
try
{
myFilesDir = new File( getFilesDir()+"/MyDir");
if(! mfilesDir.exists() )
myFilesDir.mkdirs();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(myFilesDir.toString()+"/temp.jpeg")));
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No camera: " + e );
}
catch ( Exception e )
{
Log.e( TAG, "Cannot make photo: " + e );
}
}`

camera activity gives null pointer exception

in my camera intent:
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this part gives me a null pointer exception.
can anyone explain why and what need to be changed??
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, TAKE_PICTURE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// 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
}
}
}
Try the following,
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}

Categories

Resources