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.
Related
public class addBoard extends AppCompatActivity {
private final int GET_GALLERY_IMAGE = 200;
Uri image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addboard);
final EditText EDTITLE = findViewById(R.id.editTitle);
final EditText EDTEXT = findViewById(R.id.editText);
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Button addPhoto = findViewById(R.id.photo);
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, GET_GALLERY_IMAGE);
}
});
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), image);
imgView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button backButton = findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Input_Title", EDTITLE.getText().toString());
intent.putExtra("Input_Text", EDTEXT.getText().toString());
intent.putExtra("Input_Image", image);
setResult(RESULT_OK, intent);
finish();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_GALLERY_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectImage = data.getData();
image = selectImage;
}
}
}
If you run this code in another project, there is no error, but if you use it in this project, you will get an error. Why is that?
Error :Caused by: java.lang.NullPointerException: uri
at com.example.toolbar.addBoard.onCreate**(addBoard.java:45)** // blue line
An error occurs during the operation to place Uri as bitmap in imageView.
Hello I am trying to crop an image from android camera. I camera is activted and the activity to crop the image is also activated.
But, I am not being able to pass the cropped image to another activity.
I searched, I cant find a solution. What iam doing wrong? Maybe, It is because the putExtras?
lib page:
https://github.com/ArthurHub/Android-Image-Cropper
my PhotoFragment.java
public class PhotoFragment extends Fragment{
private static final String TAG = "PhotoFragment";
//constants
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: Started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching the camera.");
// Create intent to Open Image
Intent galleryIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(galleryIntent, CAMERA_REQUEST_CODE);
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}else{
return false;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("APP_DEBUG", String.valueOf(requestCode));
try {
// When an Image is picked
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
CropImage.activity(selectedImage)
.setGuidelines(CropImageView.Guidelines.ON)
.setMinCropResultSize(800, 800)
.setMaxCropResultSize(1000, 1000)
.start(getContext(), this);
}
// when image is cropped
else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Log.d("APP_DEBUG",result.toString());
if (resultCode == Activity.RESULT_OK) {
Uri resultUri = result.getUri();
Log.d("APP_DEBUG",resultUri.toString());
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
//pofilePic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "sssss", Toast.LENGTH_SHORT).show();
if(isRootTask()) {
try {
Log.d(TAG, "onActivityResult: received new bitmap from camera" + bitmap);
Intent intent = new Intent(getContext(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException" + e.getMessage());
}
}else {
try {
Log.d(TAG, "onActivityResult: received new bitmap from camera" + bitmap);
Intent intent = new Intent(getContext(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException" + e.getMessage());
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
else {
Toast.makeText(getActivity(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong"+e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
and My NextActivity.java is:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mcaption = (EditText) findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity.");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
// upload the image to firebase
Toast.makeText(NextActivity.this,"Attempting to upload a new photo", Toast.LENGTH_SHORT).show();
String caption = mcaption.getText().toString();
// check if the intent came from gallery or from the camera
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl, null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null, bitmap);
}
}
});
setImage();
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = (ImageView) findViewById(R.id.imageShare);
// check if the intent came from gallery or from the camera
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
// UniversalImageLoader handles null , oder wise we should check is image is null
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new Bitmap");
image.setImageBitmap(bitmap);
}
}
I expect to get the cropped image in the ImageView image of the NextActivity.java
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.
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();
}
}
}
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.