Android - Cannot set gallery image to ImageView - android

I've looked through tons of posts and cannot figure out why I can't get this to work. All I want to do is have the user click a button that opens up the gallery app. Then the user selects a picture which automatically closes out the gallery and goes back to my application where it automatically sets that image to an ImageView.
So far, I have it working all the way up until it goes back to my application. It seems to all be fine but the image never shows up in the ImageView.
Here is the XML code for the ImageView:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal" />
At the beginning of my activity I set the ImageView with this:
ImageView targetImage;
And here is the rest of my code to get the image and set it to my ImageView. There is a button that launches "setGunImage".
public void setGunImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
targetImage.setImageURI(selectedImageUri);
}
}
}
I have tested it on both the simulator with the sd card enabled and an image loaded into and also on a real device. Both give the same behavior. It goes through the gallery steps fine but when it goes back to my application there is no image loaded in the ImageView.
I tried changing the data to a bitmap and setting that but it never showed up either. I know it's probably something super simple that I'm just not seeing so hopefully a fresh pair of eyes can point me in the right direction. Thanks.

I think Imran solution should work fine .............. and you can also try this way
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
targetImage = (ImageView)findViewById(R.id.imageView1);
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
from link

you are passing URI in setImageURI so fist get path of image using MediaStore.Images.Media.DATA and URI then pass path of image in setImageURI.
try this way:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
String selectedImagePath=getPath(selectedImageUri);
targetImage.setImageURI(selectedImageUri);
}
}
}
private String getPath(Uri uri)
{
String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(uri,projection,null,null,null);
int column_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Related

startActivityForResults not working when the child activity calls another activity

I have 3 activities say A, B and C.
A calls B.
When B doesn't call C it returns to A. But when B calls C it doesn't return to A, the app stops.
Now the real problem is, from activity A I want to call an image picker and crop the image. That's Activity B which crops and calls C for picking image.
Activity A:
iv_profile_pic.setOnClickListener(new View.OnClickListener() {//iv_profile_pic is an ImageView
#Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,profile_pic_chooser.class);
i.setFlags(0);
MainActivity.this.startActivityForResult(i, 999);
Toast.makeText(getApplicationContext(),"Reached",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999) {
Bitmap image=data.getParcelableExtra("picture");
iv_profile_pic.setImageBitmap(image);
}
}
Activity B:
It has 2 buttons. Load and Crop. Load when clicked calls ImageChooserIntent and chooses an image which is opened in B with guidlines to crop.
Crop when clicked should return back to A the cropped image.
If crop is called without calling load, it returns to A with null, of-course.
But if Load is clicked first and then Crop is called, the app simply stops.
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", cropped);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
I got a workaround. The most probable problem I was facing was:
I was using an external library for cropping the image. This library did 2 things.
First, selected an image using imageChooser intent.
Second, Cropped that image.
After the library cropped the image, it wasn't saving the cropped image in local/external storage. But I was trying to pass it back to parent directory.
There's the problem. The file doesn't exist and still I am trying to use it. The application terminates.
So my workaround was,
• Save the bitmap in storage
• Pass the Uri to parent
• Extract that Uri from child
• Make bitmap from that Uri
• Apply on the ImageView
So Activity B had:
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
File externalStorageDirectory = Environment.getExternalStorageDirectory();
externalStorageDirectory= new File(externalStorageDirectory , "FOLDERNAME");
if(!createDirIfNotExists(externalStorageDirectory)){
Toast.makeText(this,"Failed creating Directory!",Toast.LENGTH_SHORT).show();
}else{
File filename=new File(externalStorageDirectory, String.valueOf(Calendar.getInstance().getTimeInMillis())+".PNG");
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
cropped.compress(Bitmap.CompressFormat.PNG, 100, out); // cropped is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", Uri.fromFile(filename));
setResult(RESULT_OK, returnIntent);
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Toast.makeText(this,mCropImageUri.toString(),Toast.LENGTH_SHORT).show();
}
And Activity A had:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999 && resultCode==RESULT_OK) {
Uri path=data.getParcelableExtra("picture");
Bitmap bitmap=null;
try {
bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), path);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this,path.toString(),Toast.LENGTH_SHORT).show();
if (bitmap!=null){
iv_profile_pic.setImageBitmap(bitmap);
}
}
Maybe my problem statement is wrong, but workaround works. Any edits/suggestions
are 100% welcome. Just in-case someone like me gets stuck, this might help!

when i choose photo from gallery or take a picture from camera my photo is rotating?

im choosing a photo from gallery or taking a picture from camera and when it sets to an ImageView it's getting rotate , how can i fix it to become without rotate ?
public void setNewImage() {
new android.app.AlertDialog.Builder(getActivity())
.setPositiveButton("camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(takePicture, 0);
}
})
.setNegativeButton("gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(pickPhoto, 1);
}
})
.show();
}
and here im setting the image to imageview :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
NewpostFragment.post_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
/* Uri picUri = data.getData();
filePath = getPath(picUri);
img.setImageURI(picUri);*/
}
break;
case 1:
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
/*Uri picUri = data.getData();
filePath = getPath(picUri);
img.setImageURI(picUri);*/
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
NewpostFragment.post_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
First, ACTION_IMAGE_CAPTURE will not give you a Uri via getData() in onActivityResult(). While some buggy camera apps may do that, most will not. Your choices are:
Provide EXTRA_OUTPUT on the ACTION_IMAGE_CAPTURE Intent, in which case the photo should be stored in the location identified by the Uri that you put into EXTRA_OUTPUT, or
Do not provide EXTRA_OUTPUT, and use getParcelableExtra("data") to get a thumbnail from the camera app
See this sample app for using ACTION_IMAGE_CAPTURE with EXTRA_OUTPUT.
In terms of orientation, if you go down the EXTRA_OUTPUT path, you can use android.support.media.ExifInterface to find out the orientation of the photo, then do something to rotate the image to match (e.g., rotate the ImageView).
See this sample app for using ExifInterface (though I am using a different implementation than android.support.media.ExifInterface).

Passing ImageView from one activity to another activity

I have been trying to create an android app with the integration of Adobe creative SDJ but I have encountered some problems.
I have created an Activity where one launches camera or gallery to select an image for editing it. The camera launches and the photo is captured and saved in this path:
storage/emulated/0/Pictures/myAppName/myImage.jpg
It is also supposed to be displayed in an ImageView in the same activity but it isn't being displayed. In another activity, I have integrated the ImageEditing UI of the creative sdk from Adobe which needs an imageUri as an input image.
Here are my codes for displaying Image in the ImageView:
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// camera codes
String path = "storage/emulated/0/Pictures/Touch/touch.jpg";
resultImageView.setImageDrawable(Drawable.createFromPath(path));
// gallery codes
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
resultImageView.setImageURI(imageUri);
}
}
How can I convert the ImageView into Uri and send it to the next activity? Thanks in advance!
I think you are doing wrong for camera code. as you say your gallery code is working fine .try this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 0) {
//taking clicked image from Intent of activity
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");//storing image
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//adding clicked image to ImageView
imgClicked.setImageBitmap(thumbnail);
Hope this will help you..:-)

Retrieving a photo from photo gallery

I have found this code and trying to implement in my application, it open the gallery, let's me select a photo, then the applications stops working and closes.
It's my first time trying to upload an image to mysql, and i'm stuck at the very beginning.
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filePath = data.getData();
try
{
bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
}
}
Uri filePath = data.getData();
This will be meaningless for most Uri values.
The best solution to populate an ImageView from a Uri is by using a third-party image loading library, such as Picasso.
If you insist upon doing this yourself, you will need to fork a background thread, use a ContentResolver and openInputStream() to get an InputStream on the content backed by the Uri, use BitmapFactory and decodeStream() to get a Bitmap, then (on the main application thread) update the ImageView with the Bitmap.

Populating listview from sdcard images

I would like to add images from my sdcard to my listview. Currently I can choose picture from my sdcard by the button click on my UI. The implementation to choose picture is this:
sendPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mybyte=null;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
}
});
The onActivityResult of this implementation is:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
currImageURI = data.getData();
myvariable=getRealPathFromURI(currImageURI);
try {
mybyte=fileToByteArray(myvariable);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My aim is convert "mybyte", which is a byte[] variable, to an image and put the image on my listview.
Any help is appreciated.
With such an implimentation,transforming byte[] to Bitmap and store Bitmaps in your adapter source list, you will get an OutOfMemmory error. Will be better to store in your ArrayList not the Bitmap but the path to it, you get it from cursor after chosing bitmap from galery, and load the Bitmap in an AsyncTask in the getView method of your CustomAdapter.Google has a good example on how to do a fancy ListView with ImageViews HERE

Categories

Resources