Android Camera passing bitmap from Camera Intent to MainActivity - android

I am trying to take a picture and set it in my MainActivity to an ImageView.
I want to have my camera activity as a seperate class so i tried the following:
MainActivity:
public void onClick(View v) {
switch (v.getId()) {
case R.id.action_button:
Intent camera = new Intent(MainActivity.this,Camera.class);
startActivityForResult(camera ,CAMERA_IDENTIFITER);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","Sucessfully callbacked!"); //This one wont be executed!
switch(requestCode) {
case (CAMERA_IDENTIFITER) : {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
mImageView.setImageBitmap(bitmap);
}
break;
}
}
}
And this is my camera Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
pm = getPackageManager();
}
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult){
dispatchTakePictureIntent();
}
}
public void dispatchTakePictureIntent() {
if (takePictureIntent.resolveActivity(pm) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch {...}
if (photoFile != null) {
pictureTaken = true;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
Log.d("onActivityResult","finish() executed!"); //This one gets executed!
finish();
} catch {...}
}
}
The camera intent is starting properly but when i take a picture i dont get back to the onActivityResult in my MainActivity , i'm stuck in the Camera intent.

Your onStart() gets called after onActivityResult() is being executed. Hence starting camera intent again and again. Put Logs and test your self.
To solve the issue
Keep a boolean variable in your activity isFronActivityResult. Keep default value as false and do isFromActivityResult = true; inside onActivityResult(). In onStart do the following:
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult)
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
isFromActivityResult = true;// add this line
finish();
} catch {...}
}
}

Related

How can I handle camera and gallery output simultaneously, without using 2 times onActivityResult?

I have a dialogue, which asks you to choose if to take a picture or to upload one from gallery. The taken/chosen image I set as background on a Button. how can I handle both outputs, as I can't use 2 times onActivityResult?
Here is the method that invokes the camera:
private void invokeCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
And the method that lets you choose from a gallery:
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
I handle the image received from the camera on the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = (Bitmap) extras.get("data");
if (photo != null) {
findViewById(), and whose background you want to update
if (Build.VERSION.SDK_INT > 16) {
imageUploader5.setBackground(new BitmapDrawable(getResources(), photo));
}
} else {
imageUploader5.setBackgroundDrawable(new BitmapDrawable(getResources(), photo));
}
}
}
}
}
First, make a global variable
private final static int GET_PHOTO_BITMAP = 1234;
Then do the following
private void invokeCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, GET_PHOTO_BITMAP);
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GET_PHOTO_BITMAP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GET_PHOTO_BITMAP && data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = (Bitmap) extras.get("data");
if (photo != null) {
findViewById(), and whose background you want to update
if (Build.VERSION.SDK_INT > 16) {
imageUploader5.setBackground(new BitmapDrawable(getResources(), photo));
}
} else {
imageUploader5.setBackgroundDrawable(new BitmapDrawable(getResources(), photo));
}
}
}
}
}
Here the key part is request code which is the second parameter of the startActivityForResult(Intent intent, int requestCode)
you can have different requestCodes for different operations and handle it this way in
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case code1:
//task1
break;
case code2:
//task2
break;
//and so on
}
}
but since your case both the callbakcs for startActivityForResult() are supposed to perform the same operation, you can pass same code for both the calls as I have done in the above solution. But make sure that you pass same code when the operations done in the callback are similar.

onActivityResult not working after taken photo in Moto G

private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST);
}
/*
* 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 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");
}
/*
* Recording video
*/
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST)
{
if (resultCode == RESULT_OK)
{
// successfully captured the image
// display it in image view
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
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();
}
}
}
this code is working on Google Nexus 4.4.4, but this same code is not working on Moto G 4.4.4.
I also used debugger but in the Moto G onActivityResult is not called.
Use this code:
ImageView profile=(ImageView)findviewById(R.id.imageview);
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, code);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == code) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
bmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
profile.setImageBitmap(bmp);
}
}
}
For working on all devices you don't have to put Extra in intent, and you need to get the path of image inside OnActivityResult method, Example:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
// retrieve the bitmap from the intent
bitmap = (Bitmap) data.getExtras().get("data");
Cursor cursor = getActivity().getContentResolver().query(Media.EXTERNAL_CONTENT_URI,new String[] {
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
selectedImagePath = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.e("path of the image from camera ====> ",selectedImagePath);
public void callCamera() {
//access to camara
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

Intent to take picture, if i press back, the application crashes

I call this function:
private void TakePhoto() {
LogService.log(TAG, "inTakePicture");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BlueSkyBio/media/", "test.jpg");
outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Which takes me on the next onActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
if(outputFileUri != null){
LogService.log("MainFragment", outputFileUri.toString());
String path = outputFileUri.toString();
selectedVideoPath = path.substring(7);
LogService.log("in take pic", "selectedImagePath: " + selectedVideoPath);
Intent paintActivity = new Intent(getActivity(), PaintActivity.class);
paintActivity.putExtra("selectedImagePath", selectedVideoPath);
paintActivity.putExtra("isVideo", false);
startActivity(paintActivity);
((FragmentActivity) getActivity()).finish();
} else{
// Toast.makeText(getActivity(), "No picture taken", Toast.LENGTH_SHORT).show();
Intent main = new Intent(getActivity(), FragmentActivity.class);
startActivity(main);
((FragmentActivity) getActivity()).finish();
}
}
}
This works ok, but if i call the intent to take a picture, and then press the back button, if i already took a picture before, it will load that picture, if not, it will crash, because by pressing back, it will not take a picture. What can i do to escape this situation?
I have tried to test:
if(data != null) // instead of: if(outputFileUri != null){
But this will never enter the "else" part of the code.
use these conditions:
private static final int CAMERA_PIC_REQUEST = 1337;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_PIC_REQUEST && resultCode == RESULT_OK){
log.d("something","something");
}
else if (resultCode == Activity.RESULT_CANCELED)
{
log.d("something","something");
}
}

Using intent to use Camera in Android

I am using the following code to use camera by using intent.
In the parameter of intent I am passing android.provider.MediaStore.ACTION_IMAGE_CAPTURE.
It is able to open the camera.
But the problem is that it stops unexpectedly.
The problem is that it gives null pointer exception on OnActivityResults.
I have used the below code:
public class demo extends Activity {
Button ButtonClick;
int CAMERA_PIC_REQUEST = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ButtonClick =(Button) findViewById(R.id.Camera);
ButtonClick.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View view)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// request code
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == CAMERA_PIC_REQUEST)
{
// data.getExtras()
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image =(ImageView) findViewById(R.id.PhotoCaptured);
image.setImageBitmap(thumbnail);
}
else
{
Toast.makeText(demo.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Can anyone help me to solve this problem?
Try request code 1337.
startActivityForResult(cameraIntent , 1337);
This how I use it
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1337);
do you have the following declarations in your manifest ?:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
??
I used to do the same...
here is my call to intent:
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
intent.putExtra( MediaStore.EXTRA_VIDEO_QUALITY,1);
the only slight difference between my and your code - I have file path in URI sending among call
I have used the following code and it worked!
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
final Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
im.setImageDrawable(null);
im.destroyDrawingCache();
Bundle extras = data.getExtras();
Bitmap imagebitmap = (Bitmap) extras.get("data");
im.setImageBitmap(imagebitmap);
}
}
Using intent to use Camera in Android
##
Uri imageUri;
1:-
TextView camera = (TextView)findViewById(R.id.camera);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), new Date().getTime() + "myPic.jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, IMAGE_CAMERA_REQUEST);}
2:-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == IMAGE_CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getActivity().getContentResolver().notifyChange(selectedImage, null);
ContentResolver contentResolver = getActivity().getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(contentResolver, selectedImage);
imageDialog(bitmap);
} catch (Exception e) {
Log.e("Camera", e.toString());
}
}
}
}}
I hope it's working for you.

Can i pass uri value from onActivityResult() to onClick()?

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView01 = (SurfaceView) findViewById(R.id.mSurfaceView1);
mSurfaceHolder01 = mSurfaceView01.getHolder();
mSurfaceHolder01.addCallback(EX10_04.this);
mButton02 = (Button)findViewById(R.id.buttonObj);
mButton02.setOnClickListener( new Button.OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType("audio/*");
Intent destIntent = Intent.createChooser( intent, "select audio" ); //pick up an audio file
startActivityForResult( destIntent, 0 );
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == RESULT_OK )
{
Uri uri = data.getData();
if( uri != null )
{
DrawO();//It will draw a circle
}
else
{
e.printStackTrace();
}
}
The circle not show.....
but when i put the DrawO() next to
mSurfaceHolder01.addCallback(EX10_04.this);
It draw a circle !
if i want to draw a circle in the onActivityResult event
what shuld i do ?
or if i can pass uri to onClick function ?
public void DrawO()
{
Canvas mCanvas01 = mSurfaceHolder01.lockCanvas(null);
mCanvas01.drawColor(getResources().getColor(R.drawable.white));
Paint mPaint01 = new Paint();
mPaint01.setStyle(Paint.Style.FILL);
mPaint01.setColor(getResources().getColor(R.drawable.red));
mPaint01.setStrokeWidth(1.0F);
........
.......
}
1) The circle is not drawn because the surface is not created yet. Try something like this:
boolean needDrawing = false;
public void onResume() {
if (needDrawing) {
Draw0();
needDrawing = false;
}
...
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == RESULT_OK )
{
Uri uri = data.getData();
if( uri != null )
{
needDrawing = true;//It asks to draw a circle
}
else
{
e.printStackTrace();
}
}
2) To pass the URI simply declare a field URI and assign it in onActivityResult and in onClick() check if not null, use it and invalidate it

Categories

Resources