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.
Related
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
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.
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
In my app I have functionality to record video from camera. the code works fine with all devices but with nexus-7 (android OS 4.3) i am getting null
onActivityResult(int requestCode, int resultCode, Intent data) method.
when i debug my code i noticed that Intent data is null here for nexus-7 (android OS 4.3)
please suggest some solution for it.
here is code of recordVideo method
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// set video quality
// 1- for high quality video
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
please modify your recordView method as follows :-
private void recordVideo() {
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);
}
//then in onActivityResult Method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_VIDEO_CAPTURED_NEXUS:
this.videoFromCameraNexus(resultCode, data);
break;
default:
break;
}
}
}
// videoFromCameraNexus method
private void videoFromCameraNexus(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;
}
hope this will help you.
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?