Error with image view when displaying an image by camera capturing - java

i am new to android and i am trying to make my phone cam take a picture and display it in an image view. When the image is captured, it is saved correctly but after that the app stops working when the image should be displayed in an image view. Any help is appreciated. I searched some topics but still nothing works.
Here is the code:
package myfirstapp.myapps.me.camera;
import ...
public class MainActivity extends ActionBarActivity {
ImageButton camBtn;
ImageView imageView;
ScrollView scrollView;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OpenCam(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Uri tempURI=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0)//==0 the same where startActivityForResult(intent, 0) so we are in the same process
{
switch (resultCode){
case Activity.RESULT_OK:
if(imageFile.exists())
{
Toast.makeText(MainActivity.this, "Image was saved at "+imageFile.getAbsolutePath(), Toast.LENGTH_SHORT)
.show();
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(MainActivity.this, "Image wasn't saved", Toast.LENGTH_SHORT)
.show();
}
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MainActivity.this, "Image capture was cancelled", Toast.LENGTH_SHORT)
.show();
break;
}
}
}
}
Stacktrace
Caused by: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=0, result=-1, data=null} to activity
{myfirstapp.myapps.me.camera/myfirstapp.myapps.me.camera.MainActivity}:
java.lang.NullPointerException at
android.app.ActivityThread.deliverResults(ActivityThread.java:3410) at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2817)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)

Please go through this Code:
public static final int REQUEST_IMAGE_CAPTURE = 1;
public static final int RESULT_LOAD_IMAGE = 10;
private Bitmap myBitmap;
ImageView myImage ;
public void OpenCam(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
And also,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
myBitmap= (Bitmap) extras.get("data");
myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
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();
myBitmap= BitmapFactory.decodeFile(picturePath);
// photoUri = picturePath;
myImage.setImageBitmap(myBitmap);
}
}

Why are you first saving and trying to show the saved image file. Use the returned data from onActivityResult. Before file is actually created in the memory, broadcast is sent so it can refresh the directory and show the new file. But better is to use what camera intent is returning as data.
Replace your this code
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
with this
ImageView myImage = (ImageView) findViewById(R.id.imageView);
Bitmap photo = (Bitmap) data.getExtras().get("data");
myImage.setImageBitmap(photo);

first : comment the line
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // no need to write for capture camera
second : use this line
imageFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc); // abc folder name
instead of
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Note : your code work upto kitkat but lollipop it will crash because in lollipop imageFile return null so Uri failed to convert in file . Hope your problem will resolve . and one more thing before open camera u should check that sdcard permission .

Related

Set two cropped image from camera separately in image view (Android Studio)

I am try to take two image from camera and crop image then show cropped image in two Imageview separately.
I have 2 Button to open camera one for capture first image then cropped to display it in Imageview and the second do the same thing.
My code in MainActivity
variable in calss
static int CAMERA_REQUEST_CODE = 228;
static int CAMERA_REQUEST_CODE1 = 229;
Uri pictureUri = null;
ImageView iv, iv1;
Button bt, bt1;
onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
bt = findViewById(R.id.bt);
iv1 = findViewById(R.id.iv1);
bt1 = findViewById(R.id.bt1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera1();
}
});
}
invokeCamera() and invokeCamera1() function
public void invokeCamera() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public void invokeCamera1() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE1);
}
createImageFile() function
// To create image file in pictures directory
public File createImageFile() {
// the public picture director
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // To get pictures directory from android system
// timestamp makes unique name.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
// put together the directory and the timestamp to make a unique image location.
File imageFile = new File(picturesDirectory, timestamp + ".jpg");
return imageFile;
}
onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) // resultCode: -1
{
if(requestCode == CAMERA_REQUEST_CODE ) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if(requestCode == CAMERA_REQUEST_CODE1)
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Croppedimage(result, iv); // my problem !
/*
* Here i want to use if or switch statement to can use iv1
for second camera button! HOW?
*
* example
*
* if(for first camera button)
* {
* Croppedimage(result, iv);
* }
*
* if(for second camera button)
* {
* Croppedimage(result, iv1);
* }
*
* */
}
else if(resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
}
startCropImageActivity function
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
Croppedimage function
public void Croppedimage(CropImage.ActivityResult result,ImageView iv)
{
Uri resultUri = null; // get image uri
if (result != null) {
resultUri = result.getUri();
}
//set image to image view
iv.setImageURI(resultUri);
}
____________________________________________________________________________
The problem
The cropped image for second Button set in first Imageview.
Need to find way to reach to iv1 in onActivityResult for second camera Button.
Any suggestions?
Library use for crop image
THANKS.
Looking in the issues on the GitHub respository I found this one, that seems similar to yours, you can set a custom request code when starting the crop activity.
So you can start the activity with 2 different request codes and check which one has been used on onActivityResult
private static final RC_CROP = 100;
private static final RC_CROP1 = 200;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) // resultCode: -1
{
if (requestCode == CAMERA_REQUEST_CODE) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == CAMERA_REQUEST_CODE1) {
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP1);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == RC_CROP) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on first ImageView
}
if (requestCode == RC_CROP1) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on second ImageView
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
private void startCropImageActivity(Uri imageUri, int requestCode) {
Intent vCropIntent = CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.getIntent(this);
startActivityForResult(vCropIntent, requestCode)
}
I suggest also to use a switch statement when checking the requestCode

API 25 Image capturing

i was building my app on API level 23 ,then i have changed API level to 25 the same code is not working now , here's my code :
public class expert extends Activity implements View.OnClickListener {
Button btnsetwall;
ImageButton imgbtntakeph;
ImageView Imview;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expert);
Imview = (ImageView) findViewById(R.id.imageView22);
btnsetwall = (Button) findViewById(R.id.button2);
btnsetwall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Imview.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(getBaseContext(),"Here "+ getRealPathFromURI(tempUri), Toast.LENGTH_LONG).show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
when i try to pick image from gallery or to get captured image my app crashes and i get UriString Exception
can any one tell the reason ?? and how to solve !
thanks in advance

Show selected image in another activity

I've searched on stackoverflow but never found a solution
Here is my situation:
I have a button which start an intent to pick an image
How can I resize proportionally (to keep the aspect ration) and display it on another activity (in imageview)?
I also want to save this resized image to user storage. How can I do that?
Thanks!
Here is my code
MainActivity.java
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, getString(R.string.completeaction)),
PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RequestExternal && 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 filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(MainActivity.this,PhotoResized.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
}
PhotoResized.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoresized);
img = (ImageView) findViewById(R.id.imageView1);
}
For resizing the image use sampling technique provided by dev.android here
Use Lrucache for storing images. Use technique shown here

Issue in fetching image from SD card and displaying on an ImageView

I found a program on this page to fetch image from sd card and show it on an imageView. I am getting issue at this line -
bitmap = BitmapFactory.decodeFile(picturePath);
I am getting correct value of picturePath variable but in the above line it is setting bitmap value as null. I had visited various threads and almost everyone is using this same line. I am not getting what is wrong with my code
Here is my complete code -
private Button upload;
ImageView imgView;
EditText caption;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.caption);
imgView.setImageResource(R.drawable.ic_menu_gallery);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && 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();
bitmap = BitmapFactory.decodeFile(picturePath);
imgView.setImageBitmap(bitmap);
caption.setText("Hello");
}
}
Try putting this in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
After that, make sure you have the permission enabled in the App Info screen on your device.

save path of image imported from gallery into sql database and display it in an imageview later

I'm trying to save the path of an image imported from the gallery using this method:
case R.id.media:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return true;
Here is the on activity result method:
#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) {
final 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();
mImage = picturePath;
ImageView imageView = (ImageView) findViewById(R.id.note_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setClickable(true);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewImageIntent = new Intent(android.content.Intent.ACTION_VIEW, selectedImage);
startActivity(viewImageIntent);
}
});
}
}
And here is the populate field method:
mImage =(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_IMAGE)));
But this is not working, the path doesnt get saved and when i close the activity and start the activity again, the image is gone. How can i fix this?

Categories