I am new to Android programming and I'm writing an application in Java that opens the camera take a photo and save it. I made it via Intents but I can't see onActivityResult running.
I have tested it into my phone (Samsung Galaxy S) and when I take the photo I receive a preview of that photo having two buttons one Save and the other Cancel. I haven't added something to my code to do this so I think it's something that camera does. I want after capturing the image to run onActivityResult (after I press the Save button on the preview).
But how I'm going to return a result to start onActivityResult after pressing the Button Save on the preview?
I FORGOT to tell that after i press save my entire app is terminated.
Here is my Code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TakePicButton = (Button) findViewById(R.id.TakePicture);
TakePicButton.setOnClickListener((android.view.View.OnClickListener) this);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#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) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.TakePicture){
// 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);
}
}
try the below code, you will have to modify it a bit, it will help you get From Library and From Camera both, the SELECT_PICTURE is used for getting image from library
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
myFile = new File(selectedImagePath);
else if (filemanagerstring != null)
myFile = new File(filemanagerstring);
if (myFile != null) {
Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);
break;
case CAMERA_REQUEST:
Bitmap bmp_Camera = (Bitmap) data.getExtras().get("data");
break;
default:
break;
}
}
Related
I created a button that lets the user choose between "Take picture with camera" and "Select picture from gallery".
When the picture is taken/chosen, I then display it in an ImageView of the next activity which I do by passing the URI of the file created to store the taken/selected picture.
It works as expected when the user takes a picture with his camera but when he selects an image from gallery, no image is shown in the next activity despite both intents (take a picture and select a picture) being coded the same.
My question(s): Why isn't the image displayed in the next activity ONLY when picked from the gallery ? Or how should I proceed to display it ?
Intent to open camera (working fine):
private void openCameraToTakePictureIntent() {
Log.d(TAG, "Method for Intent Camera started");
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 ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Intent to access gallery and pick an image:
private void openGalleryIntent() {
Log.d(TAG, "Method for Intent Gallery started");
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
if (galleryIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(galleryIntent, PICK_IMAGE);
}
}
}
Then here's the onActivityResult: (currentPhotoPath is the absolute path of the file created to store the image)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
}
}
Below is how the image is displayed in the following activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_picture);
Intent intent = getIntent();
String imageUri = intent.getStringExtra("USER_IMAGE");
if (imageUri != null) {
Log.d(TAG, imageUri);
} else {
Log.d(TAG, "imageUri was null");
}
image = findViewById(R.id.picture);
image.setImageURI(Uri.parse(imageUri));
}
I made sure to have the READ_EXTERNAL_STORAGE in the manifest and the xml layout is just set to "match_parent" for height and width but I can add them if it's relevant.
Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.
More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.
You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.
Note that you only have short-term access to the content identified by the Uri.
When I start the application, I upload an image using Picasso to imageview. I'm trying to make the user upload their own image. If I take a picture or select it from the gallery, I can display it in an imageview. But I would like to use SharedPreferences to display the image the next time I load the application, which I unfortunately can't do.
Here is my code.
private void showImageOptionDialog(){
final String[] options = getResources().getStringArray(R.array.image_options);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.alert_dialog_title)
.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
Intent cameraIntent = new Intent();
cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 11);
break;
case 1:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 9);
break;
case 2:
SaveSharedPreference.setAvatar(context, "none");
recreate();
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if the intent was to pick image, was successful and an image was picked
if(requestCode == 9 && resultCode == RESULT_OK && data != null){
//Get selected image uri from phone gallery
Uri selectedImage = data.getData();
//Display selected photo in image view
//head_image.setImageURI(selectedImage);
assert selectedImage != null;
SaveSharedPreference.setAvatar(context, selectedImage.toString());
}
//Handle camera request
else if(requestCode == 11 && resultCode == RESULT_OK && data != null){
//We need a bitmap variable to store the photo
Bitmap bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
//Display taken picture in image view
head_image.setImageBitmap(bitmap);
}
recreate();
}
Then I try to load using
Picasso.get()
.load(SaveSharedPreference.getAvatar(context))
.placeholder(R.mipmap.ic_launcher)
.transform(new CropCircleTransformation())
.into(head_image);
Thank you for your help
(application runs on Android 7.0+)
It's NOT a good idea to save a photo using SharedPreferences. Try caching it or use a local Database or File system to store and/or restore them
Hye.I'm doing apps that comparing two faces between image in ID Card and live capture face image.User capture image of ID card at UploadActivity.Then,front camera at LivenessActivity will be prompted to capture face image.Then UploadActivity will automatically appear along with both images that were captured.User need to click button "verify" and it will show progress bar and upload the images to server to compare them.But,what code I have to put so that it can upload both images to the server without clicking the "verify" button?Perhaps after images appear at UploadActivity,it will directly show progress bar and upload the images to the server .This is my code for your references.Thank you in advance.
UploadActivity:
btnCaptureId.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
captureImage();
}
});
// boolean flag to identify the media type, image or video
final boolean isImage = i.getBooleanExtra("isImage",true);
previewMedia(isImage);
if (fileUri != null )
{
//go to LivenessActivity to caoture image of face
Intent intent = new Intent(this, LivenessActivity.class);
startActivityForResult(intent, 2);
}
btnverify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// uploading the file to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
LivenessActivity:
#Override
public Detector.DetectionType onDetectionSuccess(DetectionFrame validFrame) {
FaceIDDataStruct dataStruct = mDetector.getFaceIDDataStruct();
if (dataStruct != null) {
face = dataStruct.images.get("image_best");
Intent returnIntent = new Intent();
returnIntent.putExtra("image_best",face);
//result go to UploadActivity
setResult(UploadActivity.PAGE_INTO_LIVENESS, returnIntent);
finish();
}
if (face == null) {
face = validFrame.getCroppedFaceImageData();
}
//do something with liveness face
return DetectionType.DONE;
}
button.performClick(); to click programmatically
This is the code that I add to make it automatically upload without click button.
#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();
}
}
if (requestCode == 2) {
if (resultCode == PAGE_INTO_LIVENESS) {
Bundle extras = getIntent().getExtras();
byte[] face = extras.getByteArray("image_best");
viewImage();
//automatically upload to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
}
}
}
Just Follow the steps
After set/show the image on imageview, start server call to upload it.
show progress dialog until the uploading finished
I want to call the android's native camera and don't save it in the storage, because I save it myself after processing image. It works almost for all devices, except Motorola XT1032 (Android 5.1, API 22). So is there a way to tell the camera not to save the picture?
Here is how I call the camera intent.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "image_"+System.currentTimeMillis()+".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
((Activity) mContext).startActivityForResult(intent, 1001);
Create the request code variable:
private static final int REQUEST_CAMERA = 1;
Open the camera:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
and in case you want to show it to the user:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
// successfully captured the image
Bitmap mBitmap = (Bitmap) data.getExtras().get("data");
if (mBitmap != null) {
imageView.setImageBitmap(mBitmap);
}
}
}
I am not sure what to search for, I have tried a few things but have not found what I need. Basically I have a default image for my app that is the logo displaying in an imageview. I have and "admin" activity where the user will be able to customize the app further. How would I allow them to change from my default logo to one of their choice and display it in the same imageview on the mainactivity (separate from where they choose it, the admin activity)??
Thanks much!
On click of button we will trigger following code:
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
On ActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
String path = "";
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
Log.d("image selected path", imageUri.getPath());
System.out.println("image selected path"
+ imageUri.getPath());
path = getRealPathFromURI(EditProfileMemberActivity.this,
imageUri);
}
//DO other stuff
}
} catch (Exception e) {
System.out.println(e);
}
}