Get image from gallery to set in imageview in fragment? [duplicate] - android

This question already has answers here:
onActivityResult is not being called in Fragment
(41 answers)
Closed 7 years ago.
How to get image from gallary to set in Imageview in fragment ? onActivityResult not called in fragment..this the code i wrote in fragment
img_user.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
img_user.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close`enter code here`();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
.show();
}
}

You can do this in this way....in your main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//call super
super.onActivityResult(requestCode, resultCode, data);
}
and inside your fragment
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// ******** code for crop image
i.putExtra("crop", "true");
i.putExtra("aspectX", 100);
i.putExtra("aspectY", 100);
i.putExtra("outputX", 256);
i.putExtra("outputY", 356);
try {
i.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
and
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0 && resultCode == Activity.RESULT_OK){
try {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
img_user.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Works perfect for me

I was also facing the same problem. Actually callback for startActivityForResult() is coming back to parent activity so you need to make
explicit call from fragment to onActivityResult() function as follows.
In Parent Activity class, override the onActivityResult() method and even override the same in Fragment Class and call as the following code.
In Parent Class:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.container);
fragment.onActivityResult(requestCode, resultCode, data);
}
In Child Class:
That Extends fragment perform your logic for image setting on imageview.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}

Please find the following code, it will work. Add this in your fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//Your stuff
}

Related

Handle the Camera in a Fragment

Excuse me for any grammatical errors.
I would like to use the camera in a different activity than mainActivity.
I found this simple tutorial on google Taking Photos Simply, that says I have to use this function:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
But, this function works fine only into the MainActivity, in fact, if I put this code in a different activity I get this error:
Cannot resolve method 'getPackageManager()'.
Some ideas?
Thank you!
Try out the following code:
static final int REQUEST_IMAGE_CAPTURE = 1;
Context c;
private void dispatchTakePictureIntent() {
Fragment yourFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
yourFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Override your parent Activity's onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Then add this to your fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
//Do something with your captured image. EX:-
try {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath))
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
Excuse me, I don't know why, when I try this application on my Nexus 5X, the photo lose the quality when it appears into the ImageView. Application image (Image View): i.imgur.com/VunFaHF.png?1 Camera Image: i.imgur.com/wjJ2a4w.jpg

Camera and gallery crashes when hard key return/back button is pressed

The camera crashes when the hard key return button is pressed. This affects both the gallery and taking photo on the camera in the app. I tried handling this by checking if the intent action() is not null. But it still crashes. Any advice is greatly appreciated.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0){
if(data.getAction() != null){
Bitmap theImage = (Bitmap)data.getExtras().get("data");
if(theImage !=null){
iv.setImageBitmap(theImage);
}
}
}
else if (requestCode == 1) {
if(data.getAction() != null){
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();
if(picturePath !=null){
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
}
***update****
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//getInfo is the Bundle
if(data !=null || getInfo !=null){
if(requestCode==0){
if(data.getAction() != null){
Bitmap theImage = (Bitmap)data.getExtras().get("data");
if(theImage !=null || getInfo !=null || data!=null){
iv.setImageBitmap(theImage);
}
}
}
Include null value checks inside onActivityResult().
Check whether Intent data is null and whether it hasExtra() before using it.
ie,
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data!=null){
// Your code
}
}

get selected image from gallery into imageview

I am facing a problem in selecting the image from a gallery and setting it into the imageview. Suppose I have two activities; mainActivity containing buttons for gallery and secondactivity containing the imageview in which the image has to be displayed.
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
Please give me the individual code for both....
here is the code to load an image from gallery:
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
with Picasso it can be done in single line and You dont need to make cursor query
I have extended it for better understanding :-
Pick Image
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
Load Image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageURI = data.getData();
Picasso.with(MainActivity1.this).load(selectedImageURI).noPlaceholder().centerCrop().fit()
.into((ImageView) findViewById(R.id.imageView1));
}
}
}
In my case work this solution
private void OpenGallery(){
Intent getImageIntent = new Intent(Intent.ACTION_GET_CONTENT);
getImageIntent .setType("image/*");
startActivityForResult(getImageIntent , IMAGE_PICKER );
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== IMAGE_PICKER && resultCode == RESULT_OK) {
Uri fullPhotoUri = data.getData();
imageView.setImageURI(fullPhotoUri);
}
}
You can share URI using putExtra("fullPhotoUri", fullPhotoUri.toString()) between activities.
Try this.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
#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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
Here some examples
http://viralpatel.net/blogs/pick-image-from-galary-android-app/
http://www.coderzheaven.com/2012/04/20/select-an-image-from-gallery-in-android-and-show-it-in-an-imageview/
To Pick Image from gallery, use this code.
btn_imageSetter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_PICKER);
}
});
Now use this Method to Set the image to the ImageViewer
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_PICKER && resultCode == RESULT_OK && null != data) {
try{
final Uri uriImage = data.getData();
final InputStream inputStream = getContentResolver().openInputStream(uriImage);
final Bitmap imageMap = BitmapFactory.decodeStream(inputStream);
iv_image.setImageBitmap(imageMap);
}
catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(context, "Image was not found", Toast.LENGTH_SHORT).show();
}
}
}

How to load an image in image view from gallery?

I have an activity, which has a button. When I click on the button it redirects me to the image gallery. I want to show the selected image in the next activity using an image view. But it is not displaying the image. The view is off screen when the image is set.
My code for selecting image and moving on next is given below. I am using no history true in my activities.
#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();
if (!(picturePath.equals(""))) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, ImageInGellary.class);
intent.putExtra("picturePath", picturePath);
startActivity(intent);
}
}
}
public class ImageInGellary extends Activity {
Button cancel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.load_image);
cancel = (Button) findViewById(R.id.buttonCancelPicture);
Intent in = getIntent();
savedInstanceState = in.getExtras();
String picturePath = savedInstanceState.getString("picturePath");
ImageView imageView = (ImageView) findViewById(R.id.img_view);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*
* Intent i = new Intent(Intent.ACTION_PICK,
* android.provider.MediaStore
* .Images.Media.EXTERNAL_CONTENT_URI);
*
* startActivityForResult(i, RESULT_LOAD_IMAGE);
*/
Intent intent = new Intent();
intent.setClass(ImageInGellary.this, MainActivity.class);
startActivity(intent);
}
});
}
}
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
To support android 11 you need to add this code in AndroidMainfest.xml
<queries>
<intent>
<action android:name="android.intent.action.GET_CONTENT" />
<data android:mimeType="image/*"/>
</intent>
</queries>
If you want to achieve it in 1 line then all you need to do is :
Picasso.with(MainActivity.this).load(data.getData()).noPlaceholder().centerCrop().fit().into((ImageView) findViewById(R.id.imageView1));
Complete Solution :-
Pick Image
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
Load Image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
//Get ImageURi and load with help of picasso
//Uri selectedImageURI = data.getData();
Picasso.with(MainActivity1.this).load(data.getData()).noPlaceholder().centerCrop().fit()
.into((ImageView) findViewById(R.id.imageView1));
}
}
}
In your situation you need to pass ImageURI to next activity
Uri selectedImageURI = data.getData();
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
Uri imageUri = data.getData();
imgView.setImageURI(imageUri);
}
}
I have solved your problem. After the image is picked, convert the image Uri to String and on your second class, convert your string back to image.
http://whats-online.info/science-and-tutorials/95/Android-get-image-from-gallery-into-imageview-programmatically/
http://whats-online.info/science-and-tutorials/49/Android-passing-multiple-data-from-one-activity-to-another/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
if(selectedImage !=null){
Intent intent=new Intent(MainActivity.this, Activity2.class);
Bundle extras = new Bundle();
extras.putString("image", selectedImage.toString());
intent.putExtras(extras);
startActivity(intent);
}
}
}
Activity2.class
Bundle extras = getIntent().getExtras();
String name = extras.getString("image");
Uri imageFinal=Uri.parse(name);

Insert an Image from the gallery on a button in Android

Im trying to do this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && 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 bmp = BitmapFactory.decodeFile(picturePath);
b[1].setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bmp), null, null);
}
But it wont set the image, no matter what. I have tried several different methods too, like using an imagebutton instead of a button and using:
imageButton.setImageBitmap(bmp)
The gallery opens fine and and the callback comes to onActivityResult(...)
but the image wont appear on the button, I have an array of buttons.
I made a rapid test. The following code works for me. If with this you still can't set the image I would check if there's a layout problem (i.e. the image is set but there's no room to show it).
activity_main.xml has just an ImageButton set to wrap_content, inside the main layout which is match_parent.
public class MainActivity extends Activity {
ImageButton imgButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_CANCELED) return;
ParcelFileDescriptor fd;
try {
fd = getContentResolver().openFileDescriptor(data.getData(), "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Bitmap bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
imgButton.setImageBitmap(bmp);
}
}

Categories

Resources