In Activity A, I want to open a dialog (CustomDialog). Inside CustomDialog, it has a button to open a camera. But the onActivityResult
not getting called after I pick an image from gallery. No toast
is getting displayed.
Activity A
private void openDialog() {
CustomDialog alert = new CustomDialog();
alert.showDialog(this);
}
CustomDialog
public class CustomDialog extends Activity{
Activity activity;
ImageView imageView;
public void showDialog(Activity activity) {
this.activity = activity;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.setCanceledOnTouchOutside(true);
imageView = (ImageView) dialog.findViewById(R.id.logoApp);
Button galleryBtn = (Button) dialog.findViewById(R.id.galleryBtn);
galleryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
galleryIntent();
}
});
dialog.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(activity,"sdddddsss",Toast.LENGTH_LONG).show();
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
onSelectFromGalleryResult(data);
}else{
// ...
}
}
}
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imageView.setImageBitmap(bm);
}
}
I follow this http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
When you show dialog in Activity A, you set reference to Activity A as param:
alert.showDialog(this);
Then inside CustomDialog, you save this reference as activity variable:
public void showDialog(Activity activity) {
this.activity = activity;
...}
This means, that this.activity
is instance of Activity A. Later in your galleryIntent(), you start activity for result like this:
private void galleryIntent() {
...
activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
}
This means that onActivityResult will be called in Activity A, not your Custom dialog, because you've used activity
variable.
You have 2 options for fix:
1) replace activity.startActivityForResult
with CustomDialog.this.startActivityForResult
2) move your onActivityResult
code from CustomDialog into Activity A