android - ANR on taking picture from gallery/camera - android

Did someone face the issue when ANR happened after choosing picture from gallery or taking a photo from camera (in my case it returns byte[] array to my app)?
How to solve it?
Upd. Here's the code how an image is picked. But this part of code didn't change and some time ago it worked (some other parts of code were changed, I don't know if it's important).
void chooseOrTakePhotoDialog(OnActivityResultListener listener) {
onActivityResultListener = listener;
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(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);
startActivityForResult(intent, REQUEST_CAMERA);
} 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"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
interface OnActivityResultListener {
void onPhotoByteArray(byte[] bytes);
}
private OnActivityResultListener onActivityResultListener;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.wtf("onActivityResult", "req="+requestCode+" res="+resultCode+" data="+data);
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case REQUEST_CAMERA:
if (onActivityResultListener != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
onActivityResultListener.onPhotoByteArray(stream.toByteArray());
}
break;
case SELECT_FILE:
Uri uri = data.getData();
try {
byte[] bytes = Helper.readBytes(getContentResolver().openInputStream(uri));
onActivityResultListener.onPhotoByteArray(bytes);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}

For the case of SELECT_FILE, you can try getting Bitmap like below.
case SELECT_FILE:
if (data != null) {
try {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getApplicationContext().getContentResolver().query(
selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = BitmapFactory.decodeFile(picturePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;

Related

Image picked from gallery is not getting set in image view

I am making a button and image view and if I click the button I want to display 3 options choose pic from gallery, take photo and cancel. And after selecting the image it should replace the image view, but when I am picking the image from gallery it is not replacing the image view and when I am choosing take photo option my application stops and gives the error:
{FileUriExposedException: file:///storage/emulated/0/temp.jpg exposed beyond app through ClipData.Item.getUri()"}
I am attaching my function which I am calling in the button onClickListener.
// function to choose profile image
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(student_form.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[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 (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageview.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
imageview.setImageBitmap(thumbnail);
}
}
}
I found the Solution for the question, now I am able to set the image to imageview by both camera and gallery, what I needed to do was add real-time permission for api23+,Change the code of selectImage() in above code.
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(student_form.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
} else if (requestCode == 2) {
String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, galleryPermissions)) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imageview.setImageBitmap(thumbnail);
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
}
}
add the following code at the end just above the last curly bracket this is to check real time permission for camera
public void EnableRuntimePermission(){
final int RequestPermissionCode = 1 ;
if (ActivityCompat.shouldShowRequestPermissionRationale(student_form.this,
Manifest.permission.CAMERA))
{
Toast.makeText(student_form.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(student_form.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
final int RequestPermissionCode = 1 ;
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(student_form.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(student_form.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
and also don't forget to call method EnableRuntimePermission(); at the start when initialising variables.
Check this example from Android:
https://developer.android.com/training/camera/photobasics.html
Basically you need to use a FileProvider now.
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
App Manifest
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
</application>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

Image from gallery, photos and camera not working always

final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 1);
So , thats How I call to open either camera or take a picture. How i read them on onactivityresult????check below the code. The problem, when image chosen from photos it works, when taken from camera it works. But when chosen from gallery folder, it doesnt work for some reason. Also some of clients are reporting me problem on sony xperia e4 phones.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK && requestCode == 1
) {
Bitmap bm = null;
try
{
Bundle extras = data.getExtras();
bm = (Bitmap) extras.get("data");
}
catch(Exception e)
{
try
{
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
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);
cursor.close();
Common.setBitmap(null);
bm = BitmapFactory.decodeFile(filePath);
BitmapFactory.decodeFile(Common.getRealPathFromURI(data.getData(), rootView.getContext()), bounds);
if(bm == null)
bm = BitmapFactory.decodeFile(Common.getRealPathFromURI(selectedImage, AddStoreActivity.this), options);
if(bm == null)
bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
}
catch(Exception e1)
{
}
}
}
} catch (Exception e) {
}
}
public static String getRealPathFromURI(Uri contentURI, Context cont) {
Cursor cursor = cont.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaColumns.DATA);
return cursor.getString(idx);
}
}
This is how I do this and it works:
private void displayAddPhotoDialog() {
final CharSequence[] items = getResources().getStringArray(R.array.photo_dialog_options);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.photo_dialog_title));
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == TAKE_PHOTO_OPTION) {
dispatchTakePictureIntent();
} else if (item == CHOOSE_FROM_LIBRARY_OPTION) {
dispatchPickImageIntent();
} else if (item == CANCEL_OPTION) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
imageUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
}
}
protected void dispatchPickImageIntent() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), GALLERY_REQUEST_CODE);
}
And your onActivityResult method should look like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
photoReceivedFromCamera = true;
getActivity().getContentResolver().notifyChange(imageUri, null);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUri);
getActivity().sendBroadcast(mediaScanIntent);
//do want you want with the uri(taken photo)
} else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
//The user cancelled the take picture action...
if (!photoReceivedFromCamera) {
//If the user has not previously taken a picture,
//this means he is cancelling the take photo process
onCancelTakePicture();
}
} else if (requestCode == GALLERY_REQUEST_CODE && data != null && data.getData() != null) {
Uri uri = data.getData();
//do want you want with the uri(selected image)
}
}

how to get filename and path of saved image after cropping

I have an app with image cropping option. After cropping the actual image, the cropped image is saved in gallery. My question is how to retrieve the file name and path of the cropped image saved in gallery.
my code is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I have tried a lot but not retrieving the file name and path. Is there any solution.
You are using startActivityForResult(), but do you override onActivityResult()? In your case you need to do the following:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
{
Uri pictureUri = data.getData();
}
}
This code gets the Uri of the picture. Then you can use this Uri to get the path, using a method like below:
private String getRealPathFromURI(Context context, Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally
{
if (cursor != null)
{
cursor.close();
}
}
}
EDIT
After you crop the Bitmap and ready to go, you can save it with something like this:
private Uri saveOutput(Bitmap croppedImage)
{
Uri saveUri = null;
// Saves the image in cache, you may want to modify this to save it to Gallery
File file = new File(getCacheDir(), "cropped");
OutputStream outputStream = null;
try
{
file.getParentFile().mkdirs();
saveUri = Uri.fromFile(file);
outputStream = getContentResolver().openOutputStream(saveUri);
if (outputStream != null)
{
croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} catch (IOException e)
{
// log the error
}
return saveUri;
}
After getting the Uri, you can get path to cropped image with the same method above.

Getting multiple images from Gallery

Right now I have an imageview. Clicking on the imageview I can get the option to select the gallery/camera intent.selecting on the required intent and the required picture I get the image in the imageview.This works fine for one single image.
How to get more than one picture.I mean the imageview[].Is there any code on this available?
Start Intent with EXTRA_ALLOW_MULTIPLE
Intent intent = new Intent( );
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent,
"select multiple images"), PICK_IMAGE_MULTIPLE);
On receiving side
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_IMAGE_MULTIPLE){
String[] imagesPath = data.getStringExtra("data").split("\\|");
}
}
}
thanks for the response but here is my code.Now please let me know how to go ahead to have multiple images shown up in multiple imageviews.Also let me know if I need a placeholder like gridview for that?
ImageView image_view = new ImageView(this);
image_view.setId(field_id);
Uri selectedImage = Uri.parse(field_val);
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
if(c.moveToFirst() && c.getCount() >= 1)
{
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(
picturePath, bitmapOptions));
image_view.setImageBitmap(thumbnail);
image_view.setTag(selectedImage);
}
else {
image_view.setImageDrawable(getResources().getDrawable(
R.drawable.camera_launcher));
}
image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getImage();
}
});
private void getImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bundle extras = data.getExtras();
try {
((ImageView) findViewById(R.id.imageid)).setImageBitmap((Bitmap) extras
.get("data"));
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
data.getDataString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,
bitmapOptions));
((ImageView) findViewById(R.id.imageid))).setImageBitmap(thumbnail);
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
selectedImage.toString());
}
}
}

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");
}

Categories

Resources