I am trying to capture an image and then display it on the screen using another activity. I am able to successfully capture the images and save them in my desired directory. However, even after hours of struggle, I am still unable to solve this problem. The touch listener is added to the screen though there's no image.
Here's the code:
private void takeImage(){ Intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, PHOTO_TAKEN); }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_TAKEN){
data.putExtra(SET_CAPTURED_IMAGE, true);
} else{
Log.d(MainActivity.DEBUGTAG, "Photo = null");
}
}
Now in another activity (ImageActivity):
addTouchListener() is called in onCreate() method of this activity.
Till here, the image is successfully captured and saved in the directory.
private void addTouchListener(){
ImageView imageView = (ImageView)findViewById(R.id.unlocker_image);
Bundle extras = getIntent().getExtras();
//The following if block is not executed
if (extras != null && extras.getBoolean(MainActivity.SET_CAPTURED_IMAGE)){
Uri imageUri= Uri.parse(extras.getString(MediaStore.EXTRA_OUTPUT));
imageView.setImageURI(imageUri);
} else {
imageView.setImageResource(R.drawable.unlocker_image);
//this is the default image added
}
imageView.setOnTouchListener(collector);
}
At this point, the touch listener is added but there's no image.
Related
I am a newbie in android app development. I have a simple question. I googled about it but couldn't find any satisfactory answer. My question is :
Can we copy and move images to another folder using startactivityforresult() method. If yes, then how can we pass the position of the selected images we want to move or copy ?
Thanks
In your main activity:
Create new ArrayList to hold selected images:
ArrayList<Model_images> selectedImages = new ArrayList<Model_Images>();
Add all selected images to selectedImages in your adapter's
onClick using:
selectedImages.add(al_images.get(position));
Then once you have the list of selected images, Build the intent and
call the activity:
Intent moveIntent = new Intent(this, MoveActivity.class);
moveIntent.putExtra("selected_images", selectedImages);
startActivityForResult(moveIntent, REQUEST_CODE); // REQUEST_CODE is a unique int value within your app for this intent.
Override onActivityResult to receive the response:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed(REQUEST_CODE)
if(requestCode==REQUEST_CODE)
{
if (resultCode == RESULT_OK){
//The called activity completed successfully.
String message=data.getStringExtra("MESSAGE"); //The message passed along with result
}
}
}
In your MoveActivity activity:
Get the passed ArrayList:
ArrayList<model_Images> selectedImages = new ArrayList<Model_Images>();
if(getIntent().getSerializableExtra("selected_images") != null)
selectedImages = getIntent().getSerializableExtra("selected_images");
Move the images to destination folder:
//Move each selected file to destination
for (Model_Images image : selectedImages{
File sourceImage = image.getFile(); //returns the image File from model class to be moved.
File destinationImage = new File("path/to/destination", "filename.extension");
moveFile(sourceImage, destinationImage);
}
//Method to move the file
private void moveFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
source.delete();
}
Set the result to calling activity once done:
// Set result back to the calling activity
Intent intent=new Intent();
intent.putExtra("MESSAGE",message); // Set a message for the calling activity
setResult(RESULT_OK,intent); //RESULT_OK represents success result
finish();//finishing activity
P.S: handling storage permission is not discussed and is required to read/write.
I have made an application where the user can take a photo and save it into their gallery in a separate folder named "SOC". This works on one of my Android devices however on the other device the user can take the picture but the image doesn't save for some reason. The device the image saves on is Android 4.2 the device it does not save the image on is Android 5.0 not sure if this has anything to do with it.
My Code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage = Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path
What i wanna do is simply add log line with file name which was recently captured. Unfortunately, application fails because of below indicated error. Code and error from stack provided below.
Thanks in advance,
Anar
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=100, result=-1, data=null} to activity
{az.justx.justx/az.justx.justx.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.net.Uri android.content.Intent.getData()' on a null object
reference
private void interceptCameraButtonClick() {
Button cameraButton = (Button) findViewById(R.id.cam);
cameraButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File image = new File(imagesFolder, "AD_" + timeStamp + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 100);
}
}
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Test", Integer.toString(resultCode));
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.i("CALLED", "Image saved to:\n" +
data.getData());
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
}
}
}
There is no requirement that the camera send back the Uri in the Intent delivered to onActivityResult(). You already know what the Uri is, as you put it in EXTRA_OUTPUT. You just need to use that value. Be sure to include it in your saved instance state, as your process may be terminated while the camera app is in the foreground.
Right now I've got an app that takes a photo via an intent. After taking the photo, I want the user to be able to confirm it and push the photo to another activity where they can add details. I'm struggling to find the correct way to pass the photo from activity to activity.
Right now, confirming the photo brings the user back to the main activity.
Here's my relevant code:
Main Activity
public void takePhoto(View view) {
// 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);
Log.d("MySecondApp",fileUri.toString());// 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);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data!=null) {
// 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
}
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MySecondApp");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MySecondApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.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;
}
I would try something like
if(resultCode == Activity.RESULT_OK)
handleCameraPhoto(data);
handle method:
private void handleCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", mImageBitmap);
startActivity(intent);
}
and then, retrieve it in your other activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
and assign it to your ImageView
ImageView iv = (ImageView)findViewById(R.id.myImageView);
iv.setImageBitmap(bitmap);
Make a constructor in your new class that takes an intent or even the image:
class newClass {
public newClass(Intent intent){
...
}
...
}
And then just make the intent the size of a thumbnail in this new class where you can do the confirmation in a popup or something similar and then have the information to be filled on the page for this class. This will also be better because if they wanted to retake the picture you could have this class which they are taken to after the picture is taken if not accepted go to take another picture.
Take a look at this blog post I wrote on how to take a full size image and a thumbnail version as well:
Use Camera Activity for Thumbnail and Full Size Image
after you did that you can extract the file path of the saved file from the file instance using getAbsolutePath() method and pass it to the following Activity.