Check if picture in imageview was captured from camera or gallery - android

I am able to capture an image from gallery or camera and put it in imageview with following code:
1. Capture image from gallery or camera:
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
// pick from file
/**
* To select an image from existing files, use
* Intent.createChooser to open image chooser. Android will
* automatically display a list of supported applications,
* such as image gallery or file manager.
*/
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
2. Show in imageview:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
bitmap = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap);
// Log.d("camera ---- > ", "" + data.getExtras().get("data"));
new ProcessUploadAvatar2().execute();
break;
case PICK_FROM_FILE:
/**
* After selecting image from files, save the selected path
*/
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap2);
break;
}
}
Now my question is how to check if the image in the imageview has been taken by camera or gallery beyond the onActivityResult() method? I try to implement something like this:
public void NetAsync() {
if (mImageView.getDrawable() != null) {
if (mImageView = bitmap) {
new NetCheck().execute();
} else if (mImageView = bitmap2) {
new ProcessUploadAvatar2().execute();
}
}
}

You can easily get this via single check of request-codes in onActivityResult()... I mean those request-codes which you've sent while calling camera/gallery intent..

Related

Android - Dialog not refresing ImageView when getting image from gallery/ camera

So i´m working on an app in which I need to show a dialog, and inside this dialog, the user can press a button to select an image from the gallery or take a photo from the camera and display that image on an ImageView inside a dialog´s ImageView.
I´m able to take the photo from the camera/gallery, and then i use it as the ImageView image, but it doesn´t show it until i press the button again, as if the layout had to be refreshed.
This is my code:
To call the dialog (get_permissions(); is used on Android M for getting the write and read storage permissions, this works correctly)
protected void createDialog() {
final Dialog dialog = new Dialog(WeightActivity.this, android.R.style.Theme_Material_Light_Dialog_Alert);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_add_weight);
Button okButton = (Button) dialog.findViewById(R.id.okButton);
final ImageButton selectImageButton = (ImageButton) dialog.findViewById(R.id.selectImageButton);
final ImageView imageView = (ImageView) dialog.findViewById(R.id.imageView);
selectImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
get_permissions();
selectImage();
imageView.setImageBitmap(bm);
}
});
dialog.show();
}
private void selectImage() {
final String[] items = WeightActivity.this.getResources().getStringArray(R.array.photo_options);
AlertDialog.Builder builder = new AlertDialog.Builder(WeightActivity.this);
builder.setTitle(R.string.weight_dialog_add_photo);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals(items[1])) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
bm = (Bitmap) data.getExtras().get("data");
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
}
}
}
Could somebody help me please??
Thanks a lot!
The problem is this,
get_permissions();
selectImage();
imageView.setImageBitmap(bm);
selectImage() starts the activity, but it doesn't block; it returns immediately. You then call setImageBitmap(), probably on a null valued bm instance field.
Move, or otherwise trigger the imageView.setImageBitmap() call in onActivityResult(), only after you have decoded the image.

cannot access onActivityResult() method in fragment

I am a beginner in Android.
I am going to make image picker from camera and file explorer.
I found out example code from google search.
But after capture, it don't call onActivityResult() Method.
So I cannot handle the capture result.
note: I am working on Fragment.
public void selectImage(){
final String [] items = new String [] {"Take Photo", "Choose Photo"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getActivity(), android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add/Change Photo");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
}
else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
getActivity().startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode,data);
// TODO Fix no activity available
if (resultCode != getActivity().RESULT_OK)
return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); // From Gallery
if (path == null)
path = mImageCaptureUri.getPath(); // From File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
}
else {
path = mImageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
imgProfile.setImageBitmap(bitmap);
super.onActivityResult(requestCode, resultCode, data);
}
calling getActivity().startActivityForResult() will result a call to onActivityResult() on the Activity hosting the Fragment and not the onActivityResult() of the Fragment it self.
If you want a call to onActivityResult() in the Fragment itself call
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
and if you want to handle it it the Activity you need to call:
getActivity().startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
Also you might want to reorganize your onActivityResult() as
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// TODO Fix no activity available
if (resultCode != getActivity().RESULT_OK)
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); // From Gallery
if (path == null)
path = mImageCaptureUri.getPath(); // From File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
imgProfile.setImageBitmap(bitmap);
}
In your fragment code you need to call the activity from the fragment. Instead of:
getActivity().startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
you need to call the following, as your code is inside a nested class.
YOUR_FRAGMENT.this.startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
without getActivity.

Saving Image path of pictures taken to Database

I'm new to android development. I am trying to create an app where when a user take a picture, it's path will be saved to the database. I am able to save and retrieve the image when it's from the gallery, But how do I save it if it's taken by camera?
Here's My Code
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Student_Profile.this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
0);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == 0) {
studentsDbAdapter.delete_Pic_byID(studID);
Uri targetUri = data.getData();
picture_location=getPath(targetUri);
// picture_location = targetUri.toString();
studentsDbAdapter.insertImagePath(studID ,picture_location);
showpic();
} }
else if (requestCode == 1) {
// How do I get The URI?
// I'm thinking that maybe if I can get the Uri
//from the new image I can save it like how I saved the image to my DB gallery style.
String pic_location=getPath(Uri);
studentsDbAdapter.insertImagePath(studID ,pic_location);
showpic();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false)
{
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if(image.exists()){
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}
Try this. It may help you.
if (fromGallery) {
data.getData()); //get image data like this
} else {
bm = (Bitmap) data.getParcelableExtra("data");
}

Not getting able to call onActivityResult Method

hi i am not able to getting call to method onActivityResult after below code.
private void ImageChooseOptionDialog() {
Log.i(TAG, "Inside ImageChooseOptionDialog");
String[] photooptionarray = new String[] { "Take a photo",
"Choose Existing Photo" };
Builder alertDialog = new AlertDialog.Builder(TabSample.tabcontext)
.setItems(photooptionarray,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
if (which == 0) {
Log.i(TAG, "Which" + which);
Log.i(TAG,
"Inside ImageChooseOptionDialog Camera");
_path = Environment
.getExternalStorageDirectory()
+ File.separator
+ "TakenFromCamera.png";
Log.d(TAG, "----- path ----- " + _path);
media = _path;
// 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);
// startActivityForResult(intent, 1212);
} else if (which == 1) {
Log.i(TAG, "Which" + which);
Log.i(TAG,
"Inside ImageChooseOptionDialog Gallary");
// Intent intent = new Intent();
// intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// startActivityForResult(Intent
// .createChooser(intent,
// "Select Picture"), 1);
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent
.createChooser(intent,
"Select Picture"), 1);
Log.i(TAG, "end" + which);
}
}
});
alertDialog.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.create().show();
}
and this is my onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Inside Onactivity Result");
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Log.i(TAG, "Inside if else Onactivity Result");
// currImageURI is the global variable I’m using to hold the
// content:// URI of the image
Uri currImageURI = data.getData();
String path = getRealPathFromURI(currImageURI);
Log.i(TAG, "Inside Onactivity Result Image path" + path);
}
}
}
please let me knew where i am doing wrong. i am calling onActivityResult method from which=1 after dialog box appears.
but not getting any log inside onActivityResult method in logcat.
This is because, you may not be getting RESULT_OK. Always first check for request code and inside that check for result code. If you are retrieving image from gallery, try following code inside onActivityResult():
if (requestCode == TAKE_PICTURE_GALLERY) {
if (resultCode == RESULT_OK) {
final Uri selectedImage = data.getData();
final String[] filePathColumn = { MediaStore.Images.Media.DATA };
final Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
final int columnIndex = cursor
.getColumnIndex(filePathColumn[0]);
final String filePath = cursor.getString(columnIndex);
cursor.close();
}
}
And use the filePath wherever you want.
I hope this solves your problem. Thank you :)
UPDATE:
Use this code to start your gallery activity:
imagePathURI = Uri.fromFile(new File(<your image path>));
final Intent intent = new Intent(Intent.ACTION_PICK, imagePathURI);
intent.setType("image/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imagePathURI);
startActivityForResult(intent, TAKE_PICTURE_GALLERY);
When you want to retrieve image from gallery, the MediaStore.EXTRA_OUTPUT refers to The name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video. So here, you have to pass the image path where u'll receive your image.
imagePathURI = Uri.fromFile(new File(<your image path>)); // here a file will be created from your image path. And when you'll receive an image, u can access the image from this image path.

Android save taken image from camera or gallery by using file system

I want to save image uri from taking camera or gallery into SQLite.
And I want to display the image which called uri from SQLite.
If I want to do this, someone said you have to save image uri into SQLite as byte, and
you can set image on imageView.
I understand the theory, but I am still getting stuck with my coding.
If it is true, I want to save formatted image into sdcard or somewhere.
someone said use BitmapFactory and decodeResource.
and call the uri from R.drawable.
However, I don't know how to save image into R.drawable folder.
Could you help me? I will give you some my coding.
I am fighting with saving image into SQLite and how to load it, and how to modify it during two weeks!
Sorry for really long coding. I don't know where I am now.
Thank you.
fridgeDetails.java
populateFields();
private void populateFields()
{
if (mRowId != null)
{
Cursor data = mDbHelper.fetchItem(mRowId);
startManagingCursor(data);
//load image from sqlite
byte[] blob = data.getBlob(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_IMAGE));
mImageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
nameEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
categoryEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
expired_Date_Btn.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
}
else{
expired_Date_Btn.setText(
new StringBuilder()
.append(mDay).append("/")
//month is 0 based. Then add 1
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
}
}
//create dialog for taking image
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
}
}
else
{
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
//image chooser
startActivityForResult(Intent.createChooser(galleryIntent, "Complete action using"), PICK_FROM_GALLERY);
}
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set", Toast.LENGTH_SHORT).show();
saveState();
setResult(RESULT_OK);
finish();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bundle extras = data.getExtras();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 200, false);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
Bitmap bt=Bitmap.createScaledBitmap(bitmap, 200, 200, false);
mImageView.setImageBitmap(bt);
break;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveState();
}
#Override
protected void onPause()
{
super.onPause();
saveState();
}
#Override
protected void onResume()
{
super.onResume();
populateFields();
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date, image);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date, image);
}
}
public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
byte[] imageByteData = imageByteStream.toByteArray();
return imageByteData;
}
The location of your image file can be obtained from data.getData() in OnActivityResult method. You can save the location as a string in Sqlite. Then use
imageView.setImageBitmap(BitmapFactory.decodeFile(filename)
to show the image.
The default location is your app folder. If you want to store elsewhere, pass the location as in the foll code
// 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); // 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)
For more info see - http://developer.android.com/guide/topics/media/camera.html
Check this to Get the URI of Captured image
Check this for Inserting image to DB as BLOB and Retrieve it back and display.
It includes download image from Server and insert into DB, just change as it as per your requirement.

Categories

Resources