I want to take a photo from my App and save this in my own gallery. After this I need the full name of the photo. With
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
this.startActivityForResult(takePictureIntent, actionCode);
}
the photo will be saved in the default gallery. If I read the documentation right than I can set the name with
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, "MyFileName");
How can I create my own gallery and save the image there instead of the default gallery?
After taking the photo and saving in a gallery the result function will be called. How can I get besides the image the full name of the file.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case actionCode:
// get the image
InputStream stream = this.getContentResolver().openInputStream(data.getData());
// How to get the file name?
break;
default:
}
}
After setting the name with the extra the onActivityResult function won't be called. Without this extra I get the image to utilize.
Capture image like this:
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
getOutputMediaFileUri like this:
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private 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()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "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;
}
return mediaFile;
}
and get saved image fileUri like this:
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
#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
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
}
}
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();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
you might want to check this open source..IT has what you need.
https://github.com/Orange1987/Android
Related
I am try to take two image from camera and crop image then show cropped image in two Imageview separately.
I have 2 Button to open camera one for capture first image then cropped to display it in Imageview and the second do the same thing.
My code in MainActivity
variable in calss
static int CAMERA_REQUEST_CODE = 228;
static int CAMERA_REQUEST_CODE1 = 229;
Uri pictureUri = null;
ImageView iv, iv1;
Button bt, bt1;
onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
bt = findViewById(R.id.bt);
iv1 = findViewById(R.id.iv1);
bt1 = findViewById(R.id.bt1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera1();
}
});
}
invokeCamera() and invokeCamera1() function
public void invokeCamera() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public void invokeCamera1() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE1);
}
createImageFile() function
// To create image file in pictures directory
public File createImageFile() {
// the public picture director
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // To get pictures directory from android system
// timestamp makes unique name.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
// put together the directory and the timestamp to make a unique image location.
File imageFile = new File(picturesDirectory, timestamp + ".jpg");
return imageFile;
}
onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) // resultCode: -1
{
if(requestCode == CAMERA_REQUEST_CODE ) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if(requestCode == CAMERA_REQUEST_CODE1)
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Croppedimage(result, iv); // my problem !
/*
* Here i want to use if or switch statement to can use iv1
for second camera button! HOW?
*
* example
*
* if(for first camera button)
* {
* Croppedimage(result, iv);
* }
*
* if(for second camera button)
* {
* Croppedimage(result, iv1);
* }
*
* */
}
else if(resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
}
startCropImageActivity function
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
Croppedimage function
public void Croppedimage(CropImage.ActivityResult result,ImageView iv)
{
Uri resultUri = null; // get image uri
if (result != null) {
resultUri = result.getUri();
}
//set image to image view
iv.setImageURI(resultUri);
}
____________________________________________________________________________
The problem
The cropped image for second Button set in first Imageview.
Need to find way to reach to iv1 in onActivityResult for second camera Button.
Any suggestions?
Library use for crop image
THANKS.
Looking in the issues on the GitHub respository I found this one, that seems similar to yours, you can set a custom request code when starting the crop activity.
So you can start the activity with 2 different request codes and check which one has been used on onActivityResult
private static final RC_CROP = 100;
private static final RC_CROP1 = 200;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) // resultCode: -1
{
if (requestCode == CAMERA_REQUEST_CODE) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == CAMERA_REQUEST_CODE1) {
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP1);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == RC_CROP) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on first ImageView
}
if (requestCode == RC_CROP1) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on second ImageView
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
private void startCropImageActivity(Uri imageUri, int requestCode) {
Intent vCropIntent = CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.getIntent(this);
startActivityForResult(vCropIntent, requestCode)
}
I suggest also to use a switch statement when checking the requestCode
I'm now making a simple android app. It's just allow user to take an Photo and then show it.
When i test it in Virtual device, it's ok. But when i download apk to my android device, after i take a photo in Back camera, the app has stopped and return to main menu. Just problem in Back Camera.
In addition, in virtual device, after taking photo, the photo will show successfully. But it's empty in my phone
In MainActivity, i click on "Take Photo", it will start the camera and same my image to folder. Then it send the path of Photo to the next activity and show it.
This is my MainActivity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ID_IMAGE_CAPTURE = 100;
Button TakePhoto, InsertPhoto, Exit;
String mCurrentPhotoPath;
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,".jpg",storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TakePhoto = (Button) findViewById(R.id.button);
InsertPhoto = (Button) findViewById(R.id.button3);
Exit = (Button) findViewById(R.id.button2);
//Start Camera
TakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
System.out.println(ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = Uri.fromFile(photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent,REQUEST_ID_IMAGE_CAPTURE);
}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ID_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
//Bitmap bp = (Bitmap)data.getExtras().get("data");
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bp.compress(Bitmap.CompressFormat.PNG, 100, stream);
// byte[] images = stream.toByteArray();
File imgFile = new File(mCurrentPhotoPath);
if(imgFile.exists()){
System.out.println("This is file"+mCurrentPhotoPath.toString());
Intent Show = new Intent(MainActivity.this, ShowPhoto.class);
Show.putExtra("image",imgFile);
startActivity(Show);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Action canceled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Action Failed", Toast.LENGTH_LONG).show();
}
}
}
}
This is The ShowPhoto Activity
public class ShowPhoto extends Activity {
private LinearLayout Image;
Button Back,Next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_photo);
Image=(LinearLayout)findViewById(R.id.linearLayout);
//Get Image from previous Activity
File image = (File)getIntent().getExtras().get("image");
Bitmap bmp = BitmapFactory.decodeFile(image.getAbsolutePath());
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, bmp.getWidth()*2, bmp.getHeight()*2, true));
Image.addView(imageView);
}
}
This is what's in my logcat when i run app
enter image description here
enter image description here
Use should ask for the permission at runtime and declare the permission in Manifest
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)
getContext(), Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
For your Manifest
<uses-permission android:name="android.permission.CAMERA"/>
I am trying to use this code snippets to upload file to the server and is giving me failed to create directory. please help
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
private static int SELECT_FILE = 3;
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private void OperationType() {
final CharSequence[] items = { "Video", "Gallery","Photo",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AdvertiserDashBoard.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Video")) {
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support video camera\nplease choose Ads from your gallery",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
}else{
recordVideo();
}
} else if (items[item].equals("Gallery")) {
chooseImageFile();
}else if (items[item].equals("Photo")) {
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera\nplease choose Ads from your gallery",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
}else{
captureImage();
}
}
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
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);
}
private void chooseImageFile() {
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
fileUri = getOutputMediaFileUri(SELECT_FILE);
intent.setType("*/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(Intent.createChooser(intent, "Select File"),
SELECT_FILE);
}
/**
* Launching camera app to record 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);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"images");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("TAG", "Oops! Failed create "
+ "images" + " 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 if (type == SELECT_FILE) {
// mediaFile = new File(mediaStorageDir.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
// }
else {
return null;
}
return mediaFile;
}
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;
}
}
#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
// launching upload activity
launchUploadActivity(true);
} 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
// launching upload activity
launchUploadActivity(false);
} 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();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(AdvertiserDashBoard.this, UploadLiveActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
outState.putParcelable("file_uri", fileUri);
// Save the state of the WebView
m_webview.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
fileUri = savedInstanceState.getParcelable("file_uri");
// Restore the state of the WebView
m_webview.restoreState(savedInstanceState);
}
Button that trigger file choose type
case R.id.btnAdsSubmit:
OperationType();
break;
default:
Please correct me i do not know what am doing wrong with code snippet
The Goal of this snippet is to choose file from Main activity and send the url to second activity for preview. from second activity user can trigger upload button to upload the file to the server.
This is my code i capture image and share successfully but can't upload video
public class CaptureActivity extends AppCompatActivity {
ShareButton shareButton;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapture;
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;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "CityApp";
static File mediaFile;
static File mediaStorageDir;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
imgPreview = (ImageView) findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapture = (Button) findViewById(R.id.btn_Capture);
shareButton = (ShareButton) findViewById(R.id.fb_share_button);
// shareButton.setFragment(this);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishImage();
// publishVideo();
}
});
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Tack Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
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);
} else if (options[item].equals("Tack Video")) {
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);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
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");
}
/**
* 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;
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();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
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());
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;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
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();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void publishImage() {
// statusUpdates= new ContactsContract.StatusUpdates(getActivity().getApplicationContext());
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Testing with android")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareButton.setShareContent(content);
}
public void publishVideo() {
Uri videoFileUri = fileUri;
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(videoFileUri)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareButton.setShareContent(content);
}
}
i want use compile 'com.facebook.android:facebook-android-sdk:4.1.0' this library thanks in advance
I want to let user capture image from camera and upload to server. So, I need an image file from captured photo.
I searched for many solutions but none of them worked.
I tried following:
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camera_intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(camera_intent, 1);
}
in onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
super.onActivityResult(requestCode, resultCode, dataIntent);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle dataBundle = dataIntent.getExtras();
Bitmap imageBitmap = (Bitmap) dataBundle.get("data");
img_profile.setImageBitmap(imageBitmap); //getting thumbnail and setting to preview image
try{
Uri selectedImageUri = dataIntent.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, projection, null, null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
profilePicFile = new File(filePath);
cursor.close();
}
catch (Exception e){
e.printStackTrace();
}
but my I got nullPinterException saying that Uri is null. I tried almost all solutions on web but didn't work. Can anyone have any solution for this?
I had the same issue. I was able to solve this using FileObserver.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
String thumbnailPath = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH);
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
processPictureWhenReady(picturePath);
// TODO: Show the thumbnail to the user while the full picture is being
// processed.
}
super.onActivityResult(requestCode, resultCode, data);
}
private void processPictureWhenReady(final String picturePath) {
final File pictureFile = new File(picturePath);
if (pictureFile.exists()) {
// The picture is ready; process it.
} else {
// The file does not exist yet. Before starting the file observer, you
// can update your UI to let the user know that the application is
// waiting for the picture (for example, by displaying the thumbnail
// image and a progress indicator).
final File parentDirectory = pictureFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath(),
FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
// Protect against additional pending events after CLOSE_WRITE
// or MOVED_TO is handled.
private boolean isFileWritten;
#Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
// For safety, make sure that the file that was created in
// the directory is actually the one that we're expecting.
File affectedFile = new File(parentDirectory, path);
isFileWritten = affectedFile.equals(pictureFile);
if (isFileWritten) {
stopWatching();
// Now that the file is ready, recursively call
// processPictureWhenReady again (on the UI thread).
runOnUiThread(new Runnable() {
#Override
public void run() {
processPictureWhenReady(picturePath);
}
});
}
}
}
};
observer.startWatching();
}
}
Here is the link that I refer to solve the issue. Its for Google glass but works fine on any Android device.