Using intent to use Camera in Android - 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.

Related

Get Image from the Gallery and Show in ImageView

I need to get an image from the gallery on a button click and show it into the imageview.
I am doing it in the following way:
btn_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImageFromAlbum();
}
});
The method Definition is as:
private void getImageFromAlbum(){
try{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}catch(Exception exp){
Log.i("Error",exp.toString());
}
}
The activity result method is
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image_view.setImageBitmap(bmp);
//to know about the selected image width and height
Toast.makeText(MainActivity.this, image_view.getDrawable().getIntrinsicWidth()+" & "+image_view.getDrawable().getIntrinsicHeight(), Toast.LENGTH_SHORT).show();
}
}
The Problem
The problem I am facing is when the image resolution is high suppose that if the image size is of 5mp to 13mp. It won't loads up and show up into the image view.
But the images with the low width and height are successfully loading into the image view!
Can somebody tell me any issues with the code and what I am doing wrong? I just want to import the camera images from the gallery and show them in the image view!
you can try this.
paste this code in your button click event.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
and below code is your on activity result
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
I hope it is helpful for you.
I use this code:
This code used to start gallery activity.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
And get the result in:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
switch (requestCode){
case GALLERY_REQUEST:
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
carImage.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception " + e);
}
break;
}
}
And don't forget to declare permission in AndroidManifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Because OnActivityResult method is deprecated, proper way nowadays with AndroidX Activity, is Activity Result APIs, and that recommended way, see docs
"registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity."
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
previewImage.setImageURI(uri);
}
});
And simply call
mGetContent.launch("image/*");
when needed.
startActivityForResult() is deprecated. Android introduced Activity Result Api for same purpose.
This is how to implement Activity Result
ActivityResultLauncher<Intent> imagePickerActivityResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
Uri imageUri = result.getData().getData();
Glide.with(this)
.load(imageUri)
.into(R.id.profileImageView);
}
}
}
);
Call above code by calling launch() with intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
imagePickerActivityResult.launch(galleryIntent);
I try all the solutions above but they don't work for me . I saw a code from tutorialspoint website and it works for me very well this is the code :
final int PICK_IMAGE = 100;
Button button = findViewById(R.id.button33);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
});
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri imageUri;
ImageView imageView = findViewById(R.id.image_main_galary);
if (resultCode == RESULT_OK && reqCode == 100){
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
the most important issue : don't forget PERMISSION :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

How to preview image in image view after picture taken from camera

http://www.c-sharpcorner.com/UploadFile/9e8439/how-to-make-a-custom-camera-ion-android/I have made a custom camera app and after click a picture i want to preview it in an image view but when i am previewing it in image view,image is being scaled from actual size of picture.
his is how I made it work for me! Assuming you are capturing an image, and would like to show the captured image in a new Activity, you can follow this way:
First on the click of button you can:
public void cameraFuture(View view) // <-- onClick() method of Camera Button
{
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Then on the onActivityResult() method, you can do this way:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PIC && resultCode==RESULT_OK){
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
Intent bitIntent = new Intent(this, CameraTake.class);
bitIntent.putExtra("imageUri", outPutfileUri);
startActivity(bitIntent);
finish();
}
}
And in the next Activity, you can receive the file this way:
Intent receiveIntent = getIntent();
uri = receiveIntent.getParcelableExtra("imageUri");
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
receiveImg= null;
} else {
receiveImg= extras.getString("PASSER");
}
} else {
receiveImg= (String) savedInstanceState.getSerializable("PASSER");
}
File imgFile = new File(Environment.getExternalStorageDirectory(),"MyPhoto.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.camOut);
myImage.setImageBitmap(myBitmap);
}
Hope it helps!
This link completely described what you want. Here is the summary:
1- Add this to the Manifest:
< uses-feature android:name="android.hardware.camera" android:required="true" />
2- Add this line to your class:
static final int REQUEST_IMAGE_CAPTURE = 1;
3- call this method where you want to open camera:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
4- Override onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setImageBitmap(imageBitmap);
}
}
I hope it help you.

Draw bitmap in different activity

So my app should capture image with intent then draw that image in different activity, but it doesn't work. Here is my code:
Main activity:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 2);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Intent k = new Intent(MainActivity.this, FullActivity.class);
startActivity(k);
}
}
Second activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = imageUri;
iv.setImageBitmap(bp);
}
Can someone help me and show where the problem is. Thanks in advance.
You need to pass the Uri as a string with the Intent in your MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Intent k = new Intent(MainActivity.this, FullActivity.class);
k.putExtra("uri", imageUri.toString());
startActivity(k);
}
}
Then get the string in your FullActivity and parse it to a Uri, then use that to set your ImageView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
String uriString = getIntent().getStringExtra("uri");
Uri selectedImage = Uri.parse(uriString);
// you may also need to call imageView.setImageURI(null); here
// or get the bitmap first to use imageView.setImageBitmap();
imageView.setImageURI(selectedImage);
}
From here
Called when an activity you launched exits, giving you the requestCode
you started it with, the resultCode it returned, and any additional
data from it
Your onActivityResult never get called when starting Second activity
Try send the uri you receive in Main activity in Bundle
Uri imageUri = intent.getData();
Intent intent = new Intent(MainActivity.this, SecondActiviy.class);
intent.putExtra("mUri", imageUri.toString());
And you can get this uri on SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String uri= getIntent().getStringExtra("mUri");
Uri imageUri= Uri.parse(uri);
Bitmap bitmap=MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
}
// Global Declaration<br>
private Uri fileUri;
private static final int REQUEST_CODE_PHOTO = 101;
// Click for capture Image
fileUri = getOutputMediaFileUri(REQUEST_CODE_PHOTO); // create a file to save the image
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, REQUEST_CODE_PHOTO);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PHOTO) {
if (resultCode == RESULT_OK) {
String PATH = fileUri.getPath();
Intent k = new Intent(MainActivity.this, FullActivity.class);
k.putExtra("KEY_FOR_PATH, PATH);
startActivity(k);
}
}
}
}
// In FullActivity
String pathOfFile = getIntent().getExtras().getString("KEY_FOR_PATH");
Bitmap myBitmap = BitmapFactory.decodeFile(pathOfFile);
//Now set myBitmap in ImageView
imageView.setImageBitmap(myBitmap)
// Add this method
private Uri getOutputMediaFileUri(int type){
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "YOUR IMAGE FOLDER");
if(imagesFolder != null && !imagesFolder.exists()) {
imagesFolder.mkdirs();
}
int photonum = AppTypeDetails.getInstance(MainActivity.this).getImageName();
AppTypeDetails.getInstance(ReportTab.this).setImageName(++photonum);
File image = new File(imagesFolder, String.format("image%08d.jpeg", photonum));
return Uri.fromFile(image);
}

Application get crashed when came back from camera

My application gets crashed when i came back from camera. Application works perfect on bellow 19 Android version but not working on OS version 19. i am using google nexus 7 to run this application.
i am sending you my code:
cameraButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, IMAGE_CAPTURE);
}
});
And my onActivityResult( is given bellow):
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (requestCode == IMAGE_CAPTURE) {
Uri fileUri = null;
if(imageReturnedIntent == null || resultCode != RESULT_OK){
Log.d("ResultNotOk", "resultCode"+resultCode);
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString());
for(File f : imageStorageDir.listFiles()){
if(Uri.fromFile(f).equals(this.fileUri)){
fileUri = this.fileUri;
Log.d("fileUriNew", "fileUriNew:-" +fileUri);
break;
}
}
}else if (resultCode == RESULT_OK) {
Log.d("ResultOk!!", "resultCode"+resultCode);
fileUri = imageReturnedIntent.getData();
}
//fileUri = imageReturnedIntent.getData();
Log.d("Uri", "FileUri"+fileUri);
Intent cameraIntent = new Intent(this, EditImage.class);
cameraIntent.setType("/*image");
cameraIntent.setData(imageReturnedIntent.getData());
cameraIntent.putExtra("EditMode", true);
cameraIntent.putExtra("Uri", fileUri);
Log.d("imageReturnedIntent", "imageReturnedIntent"+ imageReturnedIntent);
//if edit mode is 1, intent is from camera
cameraIntent.putExtra("EditMode", false);
startActivity(cameraIntent);
}
cameraButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String fileName = "Camera_Example.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, IMAGE_CAPTURE);
}
});
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageUri != null) {
outState.putString("cameraImageUri", imageUri.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
imageUri = Uri
.parse(savedInstanceState.getString("cameraImageUri"));
}
}

Camera freezes on android app

I'm currently trying to integrate a camera into my android app and save the picture on my device; however, when I take a picture, I can't proceed (the app works, but the camera shot freezes meaning I can take another picture and go back, but can't confirm). I was wondering if you guys could help. Please explain this as simply as possible because I'm very new at programming for android. Thanks everyone!
public class PhotoCapture extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
public static File newfile;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photocapture);
Button capture = (Button) findViewById(R.id.takepicture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ContextWrapper cw = new ContextWrapper(getBaseContext());
newfile = cw.getDir("test.jpg", Context.MODE_PRIVATE);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
uri = data.getData().toString();
Log.d("CameraDemo", "Pic saved");
Intent myview = new Intent(this, Finalpiece.class);
startActivity(myview);
}
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"/>
Use this permission before...
private static final int REQ_CAPTURE_CAPTURE__IMAGE = 0;
private String imagePath;
/**
* Start camera activity.
*/
protected void startCameraActivity() {
String imageDirectory = Environment.getExternalStorageDirectory()
+ File.separator + "surbeyImg";
File imageDirectory = new File(imageDirectory);
if (!(imageDirectory.exists())) {
imageDirectory.mkdir();
}
String imagePath = imageDirectory + File.separator + imgName+".jpg");
File file = new File(imagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
startActivityForResult(intent, REQ_CAPTURE_CAPTURE__IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
switch (requestCode) {
case REQ_CAPTURE_CAPTURE__IMAGE:
if (resultCode == RESULT_OK) {
Intent intentImg = new Intent(CameraDemo.this, ShowImg.class);
intentImg.putExtra("imagePath",imagePath);
startActivity(intentImg);
}
break;
default:
break;
}
}
after this use this code ...thanks

Categories

Resources