I am trying to develop an app which involves capturing an image, cropping it and saving it to Application database. In this process, I encountered an error, which seemed quite common but unclear:
'Intent' parameter in the 'onActivityResult' method is null.
Below is the activity code:
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScanActivity extends Activity {
ImageView imgFavorite;
//keep track of camera capture intent
final int CAMERA_CAPTURE = 1;
//captured picture uri
private Uri picUri;
//keep track of cropping intent
final int PIC_CROP = 2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
imgFavorite = (ImageView)findViewById(R.id.imageView1);
try {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_CAPTURE);
}
catch(Exception e){
String errormesage="Oops-your device doesnt support capturing images!";
Toast.makeText(ScanActivity.this,errormesage,Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
ContentResolver cr=getContentResolver();
String imageName = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
File photo=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),imageName);
Uri selectedImage=Uri.fromFile(photo);
Bitmap bp ;
try{
//user is returning from capturing an image using the camera
if (resultCode == RESULT_OK && requestCode == CAMERA_CAPTURE) {
picUri=data.getData();
//carry out the crop operation
performCrop(picUri);
bp = MediaStore.Images.Media.getBitmap(cr, selectedImage);
imgFavorite.setImageBitmap(bp);
Toast.makeText(ScanActivity.this,"Captured Successfully",Toast.LENGTH_SHORT).show();
}
else if (requestCode==PIC_CROP)
{
if(data!=null) {
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView picView = (ImageView) findViewById(R.id.imageView1);
//display the returned cropped image
picView.setImageBitmap(thePic);
// open();
//1 Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(intent, 0);
//1 startActivityForResult(intent,1);
}
}
else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Log.e(logtag,e.toString());
String errormesage="scan failed";
Toast.makeText(ScanActivity.this,errormesage,Toast.LENGTH_SHORT).show();
}
}
private void performCrop(Uri picUri){
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
System.out.println("Past intent");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
System.out.println("Past start activity for intent");
}
catch(Exception e){
//display an error message
String errorMessage = "oops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
System.out.println("exception message is :"+e.getMessage());
}
}
Related
MainActivity.java :
package com.example.dell.capcrop;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
final int CAMERA_CAPTURE=1;
private Uri picUri;
final int PIC_CROP=2;
Bundle bundle;
Bitmap bitmap;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn=(Button)findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId()==R.id.capture_btn){
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent,CAMERA_CAPTURE);
}
catch (ActivityNotFoundException anfe){
String errorMessage ="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri,"image/*");
cropIntent.putExtra("crop","true");
cropIntent.putExtra("aspectX",1);
cropIntent.putExtra("aspectY",1);
cropIntent.putExtra("outputX",256);
cropIntent.putExtra("outputY",256);
cropIntent.putExtra("return_data",true);
startActivityForResult(cropIntent,PIC_CROP);
}
catch (ActivityNotFoundException anfe)
{
String errorMessage="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request&&resultCode==RESULT_OK)
{
bundle=data.getExtras();
bitmap=(Bitmap)bundle.get("data");
img.setImageBitmap(bitmap);
Thread thread=new Thread()
{
#Override
public void run() {
try {
sleep(2000);
Intent intent=new Intent(getApplicationContext(),result.class);
bundle.putParcelable("bmp",bitmap);
intent.putExtras(bundle);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
picUri = data.getData();
performCrop();
} else if (requestCode == PIC_CROP) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
}
My app is basically a sign language interpreter and I need to remove an error. Here is the code in which there is multiple onactivityresult() definition which is causing error. I do some changes but all in vain. In this code the mobile camera capture image and show a frame in which the user crop the required part of image and show in the next activity.
This question already has an answer here:
Android camera Intent not saving in gallery [duplicate]
(1 answer)
Closed 5 years ago.
I am new to programming and especially Android. I am making a simple application where I am invoking the camera and taking a picture, the picture is then displayed in an ImageView but I also want it to be stored in the gallery when I click the button to view the stored pictures.
My Code:
package com.example.picture.app;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST = 10;
private ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get access to the image view
imgView = findViewById(R.id.imgView);
}
//this method will be called when the take photo button is clicked
public void btnTakePhotoClicked(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
public void onImageGalleryClicked(View v) {
//invoke the image gallery using n implicit intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//where do we want to find the data
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
//get a uri representation
Uri data = Uri.parse(pictureDirectoryPath);
//set the data and the type. Get all image types
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, 20);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//DID THE USER CHOOSE OK? If so code inside this code will execute
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
//WE ARE HEARING BACK FROM THE CAMERA
Bitmap cameraImage = (Bitmap) data.getExtras().get("data");
//at this point we have the image from the camera
imgView.setImageBitmap(cameraImage);
}
}
}
You can use the compress() method to save it in External storage.
You can try this
try
{
FileOutputStream out = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString() + "/bmp.png"));
cameraImage.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_SHORT);
}
Also, you have to add uses permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
When I take a picture, the picture will saved on the SD.(This works very well)
But the picture won´t shows in the imageView. Do you have any idea?
package de.example.Camera;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Cam extends Activity {
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_cam);
Button button2 = (Button) findViewById(R.id.photo);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start ActivityTwo
/*
* Intent intent = new Intent(getApplicationContext(),
* ActivityTwo.class); intent.putExtra("MyStringValue",
* editText1.getText().toString()); startActivity(intent);
*/
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
}else {
// The picture was returned
Bundle extras = intent.getExtras();
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
private Uri getOutputMediaFile() throws IOException {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DayTwentyNine");
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
if (mediaFile.exists() == false) {
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
}
return Uri.fromFile(mediaFile);
}
}
In the manifest I have are the following:
uses-feature android:name="android.hardware.camera" android:required="false"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here I have this peace of code that works fine the first function open the camera and take the picture and the second one place the image you took into an image view...
public void takePictu(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
photo3 = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo3);
imageView.buildDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo3.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
}
why the camera launches but the crop crash?
I am not getting any error message. We followed http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/
package com.example.background;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
//keep track of camera capture intent
final int CAMERA_CAPTURE = 1;
//keep track of cropping intent
final int PIC_CROP = 2;
//captured picture
private Uri picUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve a reference to the UI button
Button captureBtn = (Button)findViewById(R.id.capture_btn);
//handle button clicks
captureBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
}catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if(requestCode == CAMERA_CAPTURE){
picUri = data.getData();
performCrop();
}
//user is returning from cropping the image
else if(requestCode == PIC_CROP){
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView picView = (ImageView)findViewById(R.id.picture);
//display the returned cropped image
picView.setImageBitmap(thePic);
}
}
}
is the problem here?
private void performCrop(){
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Your picUri is getting null. thats why its giving an error while cropping an captured image, So, refer this link to crop an images. its worked for me,
Hope this will work for you.
I don't know for a fact that this is what you are seeing, but unfortunately this Intent goes to the AOSP Camera app. Not all devices have it, and worse, it isn't in lollipop anymore.
I'm currently trying to figure out if there is an equivalent in the new picture editor app from google or if I really have to start using an external library for that...
A pity not to have such a standard feature available anymore.
I Have a activity that opens the Camera by starting ACTION_IMAGE_CAPTURE Intent:
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
SimpleDateFormat dateformat = new SimpleDateFormat("ddMMyy");
File photo1 = new File(Environment
.getExternalStorageDirectory(), imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo1));
startActivityForResult(intent, 5);
After starting this intent it opens the image capture screen and sometimes after clicking on the capture button it doesn't return to my app (onActivityResult) it enforce me to take an image another time again, and it doen't close this screen only if i hit the back button.
I put a break point in OnActivityResult when debugging and it doen't stop in this method.
Here is the sample application which gives option to select a image from either using camera or gallery and its also allows the option of cropping image. I hope this is what you exactly want.
Please see this https://github.com/lorensiuswlt/AndroidImageCrop
Its opensource download it and explore.
Here is my code for camera intent .It works perfectly ,you can try using it .
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class PlayMenuActivity extends Activity implements OnClickListener {
Intent intent;
ImageButton cameraBtn, galleryBtn, maleBtn, femaleBtn;
static Bitmap photo;
Dialog dialog;
static String gender;
MediaPlayer mp;
protected static final int PHOTO_PICKED = 0;
private static final int CAMERA_REQUEST = 1337;
private static final int SELECT_PHOTO = 100;
private static final String TEMP_PHOTO_FILE = "tempPhoto.jpg";
protected boolean circleCrop = true;
private final static String TAG = "GetImageFromGalleryActivity";
// values for scaling image
protected int outputX = 320;
protected int outputY = 480;
protected int aspectX = 2;
protected boolean scale = true;
protected int aspectY = 3;
protected boolean return_data = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("hello", "oncreate PlayMenu");
setContentView(R.layout.play_menu_screen);//setting layout
//Image Buttons on activity screen
cameraBtn = (ImageButton) findViewById(R.id.cameraBtn_id);
galleryBtn = (ImageButton) findViewById(R.id.galleryBtn_id);
cameraBtn.setOnClickListener(this);
galleryBtn.setOnClickListener(this);
// sound played when button clicked
mp = MediaPlayer.create(this, R.raw.click);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.cameraBtn_id:
// camera intent for starting camera
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", aspectX);
cameraIntent.putExtra("aspectY", aspectY);
cameraIntent.putExtra("outputX", outputX);
cameraIntent.putExtra("outputY", outputY);
cameraIntent.putExtra("scale", scale);
cameraIntent.putExtra("category", "camera");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
break;
case R.id.galleryBtn_id:
// calling GalleryActivity for picking image from gallery
intent = new Intent(PlayMenuActivity.this, GalleryActivity.class);
startActivity(intent);
break;
default:
break;
}
}
/* creates bitmap of the captured photo */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Log.i("hello", "REQUEST cALL");
//if a camera request is made and resultcode matches then bitmap is created
if (requestCode == CAMERA_REQUEST || resultCode == Activity.RESULT_OK) {
Log.i("hello", "REQUEST cALL");
try {
Log.i("hello", "Try Call");
Bitmap bMap = (Bitmap) data.getExtras().get("data");//creating bitmap
photo = bMap;
Intent intent = new Intent(PlayMenuActivity.this,
ShowActivity.class);
intent.putExtra("category", "camera");//adding category selected ie camera
startActivity(intent);
} catch (Exception e) {
Log.i("hello", "Exception" + e.getMessage());
}
} else {
// Log.i("hello", "Else call");
Toast.makeText(PlayMenuActivity.this, "Picture NOt taken",
Toast.LENGTH_LONG).show();
}
} // fn
}// class
Hope this helps .
this is very late, but the issue here could be missing read/write permissions. I had this very issue myself and it had to do with me wanting to put the image file into my own app folder, to which the camera app had no access to.
To be safe, when sharing files betweens apps, consider using Environment.getExternalStoragePublicDirectory(), instead of Environment.getExternalStorageDirectory().