When I was using a dialog fragment inside a activity then onActivityResult() is calling correctly but now i have changed activity to fragment due to my requirement . In that case images are not loading to imageview from camera and gallery.....
Code i was using to call in dialog fragment is...
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(in, RESULT_LOAD_IMAGE);
Code used in fragment ........
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{ // Load the images from gallery and camera
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 = getActivity().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) getActivity().findViewById(R.id.icon);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
pic = (Bitmap) data.getExtras().get("data");
icon.setImageBitmap(pic);
}
}
Code used for fragment transaction is ....
MyDialogFragment myDialogFragment = new MyDialogFragment();
myDialogFragment.show(getActivity().getFragmentManager(), "DialogFragment");
Over all code of dialog fragment.........
public class MyDialogFragment extends DialogFragment implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MY_DIALOG);
}
#Override
public void onStart() {
super.onStart();
Dialog d = getDialog();
if (d!=null){
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
d.getWindow().setLayout(width, height);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.my_fragment, container, false);
ImageButton FAB=(ImageButton)root.findViewById(R.id.imagesave);
FAB.setOnClickListener(this);
LinearLayout linearbutton=(LinearLayout)root.findViewById(R.id.linearbutton);
LinearLayout linearLayout=(LinearLayout)root.findViewById(R.id.linear);
linearLayout.setOnClickListener(this);
ImageButton text=(ImageButton)root.findViewById(R.id.imageText);
text.setOnClickListener(this);
ImageButton pencil=(ImageButton)root.findViewById(R.id.imagePencil);
pencil.setOnClickListener(this);
ImageButton gallery=(ImageButton)root.findViewById(R.id.imageGallery);
gallery.setOnClickListener(this);
ImageButton camera=(ImageButton)root.findViewById(R.id.imageCamera);
camera.setOnClickListener(this);
return root;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imagesave: {
getDialog().dismiss();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Saving");
pDialog.setMessage("please wait..............");
pDialog.setCancelable(false);
pDialog.show();
FAB.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pDialog.dismiss();
FAB.setVisibility(View.VISIBLE);
//Toast.makeText(getActivity(), "File saved successfully", Toast.LENGTH_SHORT).show();
}
}, 2000);
radioGroup.setVisibility(View.INVISIBLE);
linearLayout.setVisibility(View.INVISIBLE);
imagesize.setVisibility(View.INVISIBLE);
clear.setVisibility(View.INVISIBLE);
RelativeLayout content = (RelativeLayout) getActivity().findViewById(R.id.relative);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File myDir = new File("/sdcard/MyCollection");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream outStream;
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
i = 0;
break;
}
case R.id.linear: {
getDialog().dismiss();
break;
}
case R.id.imageText:
{
editText.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.INVISIBLE);
imagesize.setVisibility(View.INVISIBLE);
radioGroup.setVisibility(View.VISIBLE);
clear.setVisibility(View.INVISIBLE);
linearLayout.setVisibility(View.VISIBLE);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Toast.makeText(getActivity(), "You have selected text ", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
break;
}
case R.id.imagePencil: {
getDialog().dismiss();
clear.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.VISIBLE);
imagesize.setVisibility(View.INVISIBLE);
radioGroup.setVisibility(View.INVISIBLE);
linearLayout.setVisibility(View.INVISIBLE);
Toast.makeText(getActivity(),"You have selected pencil ",Toast.LENGTH_SHORT).show();
i=0;
break;
}
case R.id.imageGallery: {
getDialog().dismiss();
clear.setVisibility(View.INVISIBLE);
relativeLayout.setVisibility(View.INVISIBLE);
radioGroup.setVisibility(View.INVISIBLE);
linearLayout.setVisibility(View.INVISIBLE);
imagesize.setVisibility(View.VISIBLE);
final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);
Toast.makeText(getActivity(), "You have selected gallery", Toast.LENGTH_SHORT).show();
break;
}
case R.id.imageCamera: {
getDialog().dismiss();
relativeLayout.setVisibility(View.INVISIBLE);
clear.setVisibility(View.INVISIBLE);
radioGroup.setVisibility(View.INVISIBLE);
linearLayout.setVisibility(View.INVISIBLE);
imagesize.setVisibility(View.VISIBLE);
startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE), TAKE_REQUEST);
Toast.makeText(getActivity(), "You have selected camera", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
You need to call the activity from your fragment. Change your call to:
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
yourFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);
UPDATE:
In your dialog fragment write something like this:
final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);
Depending on your setup you may need to getSupportFragmentManager() and/or method findFragmentByTag(). It depends on how and where you added your fragment.
UPDATE 2:
final Fragment homeFragment = (HomeFragment)getActivity().getFragmentManager().findFragmentById(R.id.containerView);
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
homeFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);
If the parent activity is also overriding onActivityResult then all calls to startActivityForResult will return to the parent activity. Now, to pass that call down to all fragments in the activity is by calling the base class' implementation.
In other words, if your activity (and its fragments) need onActivityResult all you need to do is call the base activity onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//this makes sure the child fragments receive this event
super.onActivityResult(requestCode, resultCode, data);
...
}
onActivityResult will get called in parent activity of your fragment.
you need to pass this event to your fragment.
you can use interface as callback here to pass on this event.
use this code its working for me
case R.id.take_pic:
startActivityForResult(new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE),
TAKE_REQUEST);
break;
case R.id.browse_pic:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_REQUEST);
break;
and here is onActivityresult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
pic = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(pic);
}
if (requestCode == SELECT_REQUEST && resultCode == Activity.RESULT_OK) {
try {
InputStream stream = getActivity().getContentResolver()
.openInputStream(data.getData());
pic = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(pic);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
Camera taken photo or selected photo is not displaying in ImageView. I'm using the following code:
private void attachFile() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Photo"), SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA && data != null) {
Log.d(TAG, "onActivityResult: done take photo");
Uri mImageCaptureUri = data.getData();
imageView.setImageURI(mImageCaptureUri);
/*Bundle bundle = data.getExtras();
final Bitmap bitmap = (Bitmap) bundle.get("data");
mOnphotoSelectedListener.getImageBitmap(bitmap);*/
} else if (requestCode == SELECT_FILE) {
Uri selectImageUri = data.getData();
mOnphotoSelectedListener.getImagePath(selectImageUri);
//imageView.setImageURI(selectImageUri);
//Picasso.with(mContext).load(selectImageUri).into(imageView);
//Picasso.with(this).load(selectImageUri).into(imageView);
}
}
}
i have this code i hope it will work for you its correct working
i set onclick for ImageProfile and i give to user picture + crop
i hope it will work for u
private void mImage_profileOnclick() {
int persmissonCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
if (persmissonCheck == PackageManager.PERMISSION_DENIED) {
Req();
}else {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_open_device);
Button pic, gal;
pic = (Button) dialog.findViewById(R.id.pick);
gal = (Button) dialog.findViewById(R.id.gallery);
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
dialog.cancel();
dialog.dismiss();
}
});
gal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialog.findViewById(R.id.cropImageView);
Button button = (Button) dialog.findViewById(R.id.bac);
cropImageView.setImageBitmap(imageBitmap);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mImage_profile.setImageBitmap(cropImageView.getCroppedImage());
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Dialog dialogs = new Dialog(getActivity());
dialogs.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialogs.findViewById(R.id.cropImageView);
cropImageView.setImageUriAsync(selectedImage);
Button button = (Button) dialogs.findViewById(R.id.bac);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap cropped = cropImageView.getCroppedImage();
mImage_profile.setImageBitmap(cropped);
dialogs.cancel();
dialogs.dismiss();
}
});
//dialogs.create();
dialogs.show();
}
break;
}
}
//#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void Req() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "شما مجوز استفاده از دوربین یا هر چیز دیگر را به برنامه نداده اید", Toast.LENGTH_SHORT).show();
}
else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
mImage_profileOnclick();
} }
Used below code inside the onActivityResult
if (requestCode == Activity.RESULT_OK) {
File user_dp;
if (requestCode == REQUEST_CAMERA && data != null) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
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();
}
user_dp = destination;
//update_profilepic is ImageView reference
Picasso.with(getContext()).load(user_dp).into(update_profilepic);
} else if (requestCode == SELECT_FILE) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
//ivImage is image reference
ivImage.setImageBitmap(bm);
}
}
}
Instead of resultCode I have requestCode on the first line inside the if statement.
I need to get an image from the gallery on a button click and show it into the imageview.
I am doing it in the following way:
btn_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImageFromAlbum();
}
});
The method Definition is as:
private void getImageFromAlbum(){
try{
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}catch(Exception exp){
Log.i("Error",exp.toString());
}
}
The activity result method is
#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();
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image_view.setImageBitmap(bmp);
//to know about the selected image width and height
Toast.makeText(MainActivity.this, image_view.getDrawable().getIntrinsicWidth()+" & "+image_view.getDrawable().getIntrinsicHeight(), Toast.LENGTH_SHORT).show();
}
}
The Problem
The problem I am facing is when the image resolution is high suppose that if the image size is of 5mp to 13mp. It won't loads up and show up into the image view.
But the images with the low width and height are successfully loading into the image view!
Can somebody tell me any issues with the code and what I am doing wrong? I just want to import the camera images from the gallery and show them in the image view!
you can try this.
paste this code in your button click event.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
and below code is your on activity result
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
I hope it is helpful for you.
I use this code:
This code used to start gallery activity.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
And get the result in:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK)
switch (requestCode){
case GALLERY_REQUEST:
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
carImage.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception " + e);
}
break;
}
}
And don't forget to declare permission in AndroidManifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Because OnActivityResult method is deprecated, proper way nowadays with AndroidX Activity, is Activity Result APIs, and that recommended way, see docs
"registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity."
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
previewImage.setImageURI(uri);
}
});
And simply call
mGetContent.launch("image/*");
when needed.
startActivityForResult() is deprecated. Android introduced Activity Result Api for same purpose.
This is how to implement Activity Result
ActivityResultLauncher<Intent> imagePickerActivityResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
Uri imageUri = result.getData().getData();
Glide.with(this)
.load(imageUri)
.into(R.id.profileImageView);
}
}
}
);
Call above code by calling launch() with intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
imagePickerActivityResult.launch(galleryIntent);
I try all the solutions above but they don't work for me . I saw a code from tutorialspoint website and it works for me very well this is the code :
final int PICK_IMAGE = 100;
Button button = findViewById(R.id.button33);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
});
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri imageUri;
ImageView imageView = findViewById(R.id.image_main_galary);
if (resultCode == RESULT_OK && reqCode == 100){
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
the most important issue : don't forget PERMISSION :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
hello i am struck in this coding first of all i am having two image view's when we click one of them the chooser dialog box will open which is having two option 1.take photo 2.select from gallery when i select from galley everything is working fine where as the problem is,
when we select take photo option and after we had captured the image when setting its preview for the first image its working fine where as the problem here is in the second image. when we select take photo option and after capturing the photo it is replacing the image of the first image with the second image.
This is Java Code:
public class PrescriptionUpload extends ActionBarActivity {
ImageView uploadimage1, uploadimage2;
Bitmap imagemap, imagemapsec;
int imageupload = 1;
int imagesecpload = 2;
int requestcamera = 0;
Button uploadpric;
StringBuilder sb;
String uploadimg2;
Toolbar include2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prescriptionimages);
include2= (Toolbar) findViewById(R.id.include2);
setSupportActionBar(include2);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
uploadimage1 = (ImageView) findViewById(R.id.uploadimage1);
uploadimage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imageupload);
}
});
uploadimage2 = (ImageView) findViewById(R.id.uploadimage2);
uploadimage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imagesecpload);
}
});
}
private void selectimage(final int number) {
final CharSequence[] items = {"Take Photo", "Choose from Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(PrescriptionUpload.this);
builder.setTitle("Add Prescription");
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, requestcamera);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
number);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == imageupload) {
try {
imagemap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage1.setImageBitmap(imagemap);
uploadimage2.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == imagesecpload) {
try {
imagemapsec = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage2.setImageBitmap(imagemapsec);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == requestcamera) {
if (uploadimage1.getId()==R.id.uploadimage1){
Bitmap testurl = (Bitmap) data.getExtras().get("data");
uploadimage1.setImageBitmap(testurl);
uploadimage2.setVisibility(View.VISIBLE);
}else if (uploadimage2.getId()==R.id.uploadimage2){
Bitmap testurltwo = (Bitmap) data.getExtras().get("data");
uploadimage2.setImageBitmap(testurltwo);
}
}
}
}
i had solved my problem using onActivityResult and with the increment of the variable
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
If I have multiple buttons on a view to call camera intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE) and a ImageView for the preview of each image and I need to know which button called it in onActivityResult so I know which corresponding preview to use how do I pass an identifying variable? Below is current code that only works with one image.
Picture button:
final ImageButton cameraTakePhotoButton = (ImageButton) photoPromptOption.findViewById(R.id.cameraTakePhotoButton);
cameraTakePhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
final ImageView questionPhotoResult = (ImageView) findViewById(R.id.questionPhotoResult);
questionPhotoResult.setImageBitmap(thumbnail);
}
}
}
Ended up using a ListView and custom adapter then having it iterate over an ArrayList with objects of class Photo... I update the Bitmap (thumbnail) property for the Photo objects when I take the picture then refresh the ListView. This method works very well.
photoListView.setAdapter(new ArrayAdapter<Photo>(this, R.layout.photo_list_item, photosList) {
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row = null;
final Photo thisPhoto = getItem(position);
if (null == convertView) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.photo_list_item, null);
} else {
row = convertView;
}
photoPreview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
File photoDirectory = new File(Environment.getExternalStorageDirectory()+"/Pictures/appName");
if(!photoDirectory.isDirectory()) {
photoDirectory.mkdir();
}
File photo = new File(Environment.getExternalStorageDirectory()+"/Pictures/appName/", thisPhoto.getId()+"_photo.jpg");
CameraHandlerSingleton.setPictureUri(Uri.fromFile(photo));
CameraHandlerSingleton.setPhotoId(thisPhoto.getId());
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
return row;
}
});
Then my onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST) {
Uri selectedImage = CameraHandlerSingleton.getPictureUri();
String photoId = CameraHandlerSingleton.getPhotoId();
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap thumbnail;
try {
thumbnail = Bitmap.createScaledBitmap(android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage), 300, 200, true);
p.setThumbnail(thumbnail);
p.setTaken(true);
} catch(FileNotFoundException e) {
Toast.makeText(this, "Picture not found.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch(IOException e) {
Toast.makeText(this, "Failed to load.", Toast.LENGTH_SHORT).show();
Log.e("Camera", e.toString());
} catch(Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
Log.e("Camera Exception", e.toString());
e.printStackTrace();
}
startActivity(getIntent());
finish();
}
}
}
Yikes. Why not use requestCode? Just tag each view with a unique code, making sure it doesn't clash with any other intents you're throwing around. Alternatively, you can use Object.hashCode() , but again, watch out for clashes.
cameraTakePhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST + v.getTag());
}
});
Then check it in your handler:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST + button1.getTag()) {
// do stuff
}
else if (requestCode == CAMERA_PIC_REQUEST + button2.getTag()) {
// do more stuff
}
}
}
If you have many buttons (or items in a ListView) that you're going to handle similarly, you can use a Map to recover the calling view from the tag.