Using Picasso to get Images from Gallery - android

I'm using Picasso to get images from the gallery. I've followed a few Questions around the same topic on SO but haven't seemed to have fixed my issue. I got my file path from onActivityResult and tried adding the "file:" + .... + ".jpg" to the file and setting it to the ImageView. But it doesn't seem to be setting to it.
public class PictureDialog extends DialogFragment {
private ImageView imageView;
private RelativeLayout relativeLayout;
private Button saveMemory;
private Bitmap bitmap, bMapScaled;
private FinishedMemorySaving fMS;
public interface FinishedMemorySaving {
void showMemory(Memory memory);
}
public PictureDialog(){
}
public static PictureDialog newInstance(Memory memory){
PictureDialog pictureDialog = new PictureDialog();
Bundle args = new Bundle();
args.putString("title", memory.getTitleMem());
args.putString("desc", memory.getDescMem());
args.putDouble("lat", memory.getLocationMem().latitude);
args.putDouble("lng", memory.getLocationMem().longitude);
args.putString("date", memory.getFormatedDate());
pictureDialog.setArguments(args);
return pictureDialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.picture_dialog, container);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final String title = getArguments().getString("title");
final String desc = getArguments().getString("desc");
final double lat = getArguments().getDouble("lat");
final double lng = getArguments().getDouble("lng");
imageView = (ImageView)view.findViewById(R.id.memPic);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
});
saveMemory = (Button)view.findViewById(R.id.saveMemory);
saveMemory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Memory memory = new Memory();
memory.setTitleMem(title);
memory.setDescMem(desc);
memory.setLocationMem(new LatLng(lat, lng));
memory.setFormatedDate(new Date());
memory.setImageMem(bitmap);
try {
saveToCloud(memory);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
String path = data.getData().getPath();
File file = new File("file:" + String.valueOf(path) + ".jpg");
Log.i("FILE ERROR", "file:" + path + ".jpg");
setPicImage(file);
//imageView.setImageBitmap(bMapScaled);
}
}
public void setPicImage(File file){
if(file == null){
Log.i("FILE ERROR", "No file " + file.getPath());
} else {
// WHERE I WANT TO SET THE IMAGE TO FROM PICASSO
Picasso.with(getContext()).load(file).centerInside().fit().into(imageView);
}
}
.........
}
I get this when I print out the File Path when I added the "file:" etc:
file:/external/images/media/6854.jpg
Just hoping to find something that might help me set it to the ImageView. Thanks.

Related

Crop Image with ArthurHub lib and pass result to other activity

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

UCrop from a fragment no requestCode being sent

I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);

How to retrieve image or 'imagePath' through Dialog-Activity Communication?

I have an ImageView opens a dialog with 2 options
to select photo from External Memory
or take new one using Camera
it opens the dialog and the dialog takes permissions successfully then open the camera or memory
but it gives me an error when i select photo from the memory or approve taken photo by camera
I am using OnPhotoReceivedListener interface in the dialog fragment to retrieve the photo and imagePath
Here is How i call the Dialog from the Activity
public class EditNoteActivity extends AppCompatActivity implements ChoosePhotoDialog.OnPhotoReceivedListener{
private String mSelectedImagePath;
private static final int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
mSelectedImagePath = null;
ImageView addImageIV = (ImageView) findViewById(R.id.ivAddImage);
addImageIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Make sure all permissions have been verified before opening the dialog
*/
for(int i = 0; i < Permissions.PERMISSIONS.length; i++){
String[] permission = {Permissions.PERMISSIONS[i]};
if(checkPermission(permission)){
if(i == Permissions.PERMISSIONS.length - 1){
Log.d(TAG, "onClick: opening the 'image selection dialog box'.");
ChoosePhotoDialog dialog = new ChoosePhotoDialog();
dialog.show(getSupportFragmentManager(), "ChoosePhotoDialog");
}
}else{
verifyPermissions(permission);
}
}
}
});
/**
* Retrieves the selected image from the bundle (coming from ChoosePhotoDialog)
* #param bitmap
*/
#Override
public void getBitmapImage(Bitmap bitmap) {
Log.d(TAG, "getBitmapImage: got the bitmap: " + bitmap);
//get the bitmap from 'ChangePhotoDialog'
if(bitmap != null) {
compressBitmap(bitmap, 70);
//TODO: Save Image and get It's Url
}
}
#Override
public void getImagePath(String imagePath) {
Log.d(TAG, "getImagePath: got the image path: " + imagePath);
if( !imagePath.equals("")){
imagePath = imagePath.replace(":/", "://");
mSelectedImagePath = imagePath;
mImgUrls += StringManipulation.imgSerialize(new String[]{imagePath, "Description"});
initRecyclerView(mImgUrls);
}
}
public Bitmap compressBitmap(Bitmap bitmap, int quality){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
return bitmap;
}
and Here is my Dialog class
public class ChoosePhotoDialog extends DialogFragment {
private static final String TAG = "ChoosePhotoDialog";
public interface OnPhotoReceivedListener{
public void getBitmapImage(Bitmap bitmap);
public void getImagePath(String imagePath);
}
OnPhotoReceivedListener mOnPhotoReceived;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_camera_or_memory, container, false);
//initalize the textview for starting the camera
TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: starting camera.");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
}
});
//Initialize the textview for choosing an image from memory
TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
selectPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: accessing phones memory.");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
}
});
// Cancel button for closing the dialog
TextView cancelDialog = (TextView) view.findViewById(R.id.tvCancelTakingPhoto);
cancelDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing dialog.");
getDialog().dismiss();
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*
Results when taking a new image with camera
*/
if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done taking a picture.");
//get the new image bitmap
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);
//send the bitmap and fragment to the interface
mOnPhotoReceived.getBitmapImage(bitmap);
getDialog().dismiss();
}
/*
Results when selecting new image from phone memory
*/
if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Uri selectedImageUri = data.getData();
File file = new File(selectedImageUri.toString());
Log.d(TAG, "onActivityResult: images: " + file.getPath());
//send the bitmap and fragment to the interface
mOnPhotoReceived.getImagePath(file.getPath());
getDialog().dismiss();
}
}
}
And this is the Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65544, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:14786 flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }} to activity {com.ahmed_smae.everynote/com.ahmed_smae.everynote.EditNoteActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.ahmed_smae.everynote.Utils.ChoosePhotoDialog$OnPhotoReceivedListener.getImagePath(java.lang.String)' on a null object reference
Do you think the problem with the interface ?
How Can I solve it ?
The error is in your On your ActivityResult method. You are accessing a method on the interface of a null object.
Please set your debugger
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
}
Then confirm the getTargetFragment() is working.
As I suspect that this is returning null or it is getting nulled out at some point before you are accessing it.
mOnPhotoReceived appears to be null in your error, so then you should set a breakpoint at the point of which you are calling getImagePath() and see the object is null. Next you just need to see where/how it is set to null.

Picture not displaying after using camera to take photo

I am trying to click a photo in a fragment and display it inside my app. After I click the photo, the imageView is not set and I don't see the photo getting displayed. Does anyone know why?
Also do you think there is a better way of writing the code for taking a picture inside the fragment?
public class ImageFragment extends Fragment{
private Uri imageUri;
private String mPath;
private ImageView image;
Bitmap bitmap = null;
private File tempPhoto;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_image, container, false);
ImageButton snap=((ImageButton)v.findViewById(R.id.snap));
image = ((ImageView) v.findViewById(R.id.image));
snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagePath;
try
{
tempPhoto = createTemporaryFile("picture", ".png");
tempPhoto.delete();
}
catch(Exception e)
{
return ;
}
imageUri = Uri.fromFile(tempPhoto);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent, 1);
}
});
return v;
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
ContentResolver cr = getActivity().getContentResolver();
try {
cr.notifyChange(imageUri, null);
File imageFile = new File(tempPhoto.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
Bitmap photo=null;
if (resultCode == 1) {
try {
photo = android.provider.MediaStore.Images.Media.getBitmap(cr, Uri.fromFile(tempPhoto));
image.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
}
You compare 'resultCode' with Activity.RESULT_OK(=-1) in onActivityResult function.
Replace:
if (resultCode == 1)
by:
if (resultCode == Activity.RESULT_OK)

Taking photos with camera and getting picture path android

My app takes a picture using the phones camera and stores the picture in the phones gallery. I would like to then get that picture path and store it in my datastore. Can someone please help me? Heres my code:
public void onClick(View v){
switch(v.getId())
{
case R.id.btnLoadPic:
//Options for the dialogue menu
final CharSequence[] items = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
/**
* Make onclick functionality for the options in the dialogue menu
*/
public void onClick(DialogInterface dialog, int item) {
// Camera option
if (item == 0){
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)){
//Toast.makeText(this, "camera", Toast.LENGTH_SHORT).show();
dispatchTakePictureIntent(11);
} else {
Toast.makeText(null, "No camera avalible", Toast.LENGTH_SHORT).show();
}
}
// Gallery option this works fine
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
//handleSmallCameraPhoto(takePictureIntent);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
ImageView mImageView = (ImageView) this.findViewById(R.id.imagePlayer);
mImageView.setImageBitmap(mImageBitmap);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
handleSmallCameraPhoto(data);
}
The last bits of codes accesses the camera and displays the picture in the imageview. How do i get that picture path in a string format?
This will help. Tested and worked!
public class MainActivity extends Activity {
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView tvPath;
ImageView picture;
File destination;
String imagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvPath = (TextView) findViewById(R.id.idTvPath);
picture = (ImageView) findViewById(R.id.idIvImage);
String name = dateToString(new Date(),"yyyy-MM-dd-hh-mm-ss");
destination = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
Button click = (Button) findViewById(R.id.idBtnTakePicture);
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();
tvPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
tvPath.setText("Request cancelled");
}
}
public String dateToString(Date date, String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
}
Dont forget to add these in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>

Categories

Resources