Android, want to delete the image after selected from the gallery - android

I'm creating a program that can select image from gallery and after selected, the text next to the image will change to "Delete" for delete the image.
I have worked on select image from gallery, and now I don't know how to make the delete function. Can someone please help!
And here is my code. Where I should put the delete.
addPhotoText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectNewsFeedImage();
}
});
.....else if (items[item].equals("Choose from Gallery")) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select File"), RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_LOAD_IMAGE && data != null) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
addPhotoIcon.setImageBitmap(bm);......

You need to get the path of the image that you have selected from the gallery first, next you need to delete that image from the sdcard using its path.
To get the path of the selected image refer this
Get filepath and filename of selected gallery image in Android
To delete the image using the path from sdcard
Android Delete Image from SD Card with OnClick

you should have to use URI here it is in the OnActivityResult
Uri selectedI = data.getData();
File file = new File(String.valueOf(selectedI));
file.delete();

Related

Android take and display photo from camera full resolution

I need to take a photo from my app and display it on an imageView, so now I´m using an intent request:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
bm = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bm);
}
}
}
The problem is that this code gets the thumbail of the image, not the image itself in full resollution, and I don´t know how to get it. I´ve searched and I have found this https://developer.android.com/training/camera/photobasics.html , but as I´m starting with this i don´t understand it.
Could somebody help me please?
Before you call CameraIntent create a file and uri based on that filepath as shown here.
filename = Environment.getExternalStorageDirectory().getPath() + "/test/testfile.jpg";
imageUri = Uri.fromFile(new File(filename));
// start default camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
imageUri);
startActivityForResult (cameraIntent, CAMERA_PIC_REQUEST);
Now, you have the filepath you can use it in onAcityvityResult method as following,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != CAMERA_PIC_REQUEST || filename == null)
return;
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageURI(imageUri);
Try out this code, It works for me.
Open camera using below code:
Intent intent = new Intent();
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ ".your folder name"
+ File.separator + "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
capturedImageUri = Uri.fromFile(File.createTempFile("your folder name" + new SimpleDateFormat("ddMMyyHHmmss", Locale.US).format(new Date()), ".jpg", file));
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, Util.REQUEST_CAMERA);
} else {
Toast.show(getActivity(),"Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
In onActivityResult retrieve path of captured image:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator
+ ".captured_Images"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = capturedImageUri.toString().replace("file://", "");
Logg.e("selectedPath1", "OnactivityResult==>>" + selectedPath1);
imageLoader.displayImage(capturedImageUri.toString(), imgCarDetails1);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is write able");
}
} catch (Exception e) {
e.printStackTrace();
}
Add this permission in Manifest file:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
None of the answers worked for me, and I couldn´t use the tutorial as when creating the FileProvider, the xml gives me an error.
Finally I found this answer which works like a charm. Android Camera Intent: how to get full sized photo?

Path of Image to be passed in Uri.parse to open an image using intent

I'm trying to open an image using intent.
The path of the image in my storage is /storage/emulated/0/nitp/download/logo.png.
My code is
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DEFAULT);
intent.setDataandType(Uri.parse("/storage/emulated/0/nitp/download/logo.png"),"image/*");
startActivity(intent);
I also tried putting file://storage/emulated/0/nitp/download/logo.png
and content://storage/emulated/0/nitp/download/logo.png
What is the path I should use?
Solved
Have to use file:///storage/emulated/0/nitp/downloads/logo.png
For Pick image from media Storage or SD Card:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
And For get the path of Image and set in ImageView:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
imgpath= MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageViewProfileImage.setImageBitmap(imgpath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this work.

onActivityResult doesn't work for Camera -Tab ActivityGrup

I want to capture image & save it to SD card. Now its working fine.
My problem is 1) after capture OK and Cancel button are avialble.When I click Ok only it need to save the image into SD card.
2) It doesn't come to onActivityResult method. I have written my onActivityResult inside the ActivityGroup class.
This code for When User click on Camera button, it will open cameara & save it
//Camera
Button btnCamera =(Button)findViewById(R.id.btnCamera);
btnCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
selectedImagePath = Environment.getExternalStorageDirectory()+"/"+retailerCode+"-"+count+".jpg";
imgName =retailerCode+"-"+count+".jpg";
count++;
File file = new File(selectedImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Bundle b = new Bundle();
b.putString("Activity", "RetailerOrderSActivity");
b.putString("RetailerName", seletctedRetailer);
b.putString("RetailerCode", retailerCode);
intent.putExtras(b);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
onPhotoTaken();
}
});
protected void onPhotoTaken() {
_taken = true;
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(CameraMainActivity.this);
dbAdapter.openDataBase();
boolean status = dbAdapter.saveImageInfo(retailerCode,strExecutive,strBusinessUnit,strTerritoryCode,imgName,visitNumber);
if(status) {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has been saved successfully" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has not been saved successfully" , Toast.LENGTH_SHORT).show();
}
dbAdapter.close();
lstCaptures = getAllImage(imgDateVal.getText().toString());
imageViewTable.removeAllViews();
loadTableLayout();
}
This is code for ActivityGroup
public class SalesActivityGroup extends ActivityGroup {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("===REQUEST=====" +requestCode);
System.out.println("==resultCode==" +resultCode); } }
Actually I need to call onPhotoTaken from onActivityResult. According current my code if the user click cancel also, it saving information to DB. Image is not captured..
This is my app image :
This is button showing after capture image:
Please anybody sort out this issue..
Thanks in advance
Check the following answer
Suppose I have a button Select & when the user clicks on the button , Camera screen will open.
btn_select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new StringBuilder(String.valueOf(System.currentTimeMillis())).append(
".jpg").toString();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, IShipdocsMobileConstants.CAMERA_ACTION);
}
});
After the user takes a photo & clicks on the Save/OK button (depends on the mobile device) , use the following code to fetch the data for the captured image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == IShipdocsMobileConstants.CAMERA_ACTION) {
if (resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
SelectedFileInfo selectedFileObj = null;
ArrayList<SelectedFileInfo> cameraArrList = new ArrayList<SelectedFileInfo>();
File fileObj = new File(capturedImageFilePath);
String fileSize = String.valueOf(fileObj.length()); //File Size
String fileName = Utils.getFileName(capturedImageFilePath); //File Name
}else if (resultCode == RESULT_CANCELED) {
// handle the condition in which the user didn't save the image
}
} else {
// handle the condition in which the request code was not CAMERA_ACTION , maybe send the user to the home/default screen
}
}
}
Problem is calling place I need to call getParent().startActivityForResult(intent, CAMERA_PIC_REQUEST); more details see here

open image form built_in gallery

I have read this link :Open an image in Android's built-in Gallery app programmatically Get/pick an image from Android's built-in Gallery app programmatically, and the code looks well.
It results with following image: http://i.stack.imgur.com/vz3S8.png, but this is not the result I want.
I want to open the gallery similar to: http://i.stack.imgur.com/ZoUvU.png.
I want to choose the pic form the folder gallery.
Do you know how to modify the code?
I used:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.gallery", "com.android.camera.GalleryPicker"));
// intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
Log.i("aa","adafdsfa");
startActivityForResult(intent, 1);
Through I get the folder gallery, but I cannot get the pic path.
File dir = new File(Environment.getExternalStorageDirectory().toString() + "/sdcard/yourfolder");
Log.d("File path ", dir.getPath());
String dirPath=dir.getAbsolutePath();
if(dir.exists() && dir.isDirectory()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// tells your intent to get the contents
// opens the URI for your image directory on your sdcard
//its upto you what data you want image or video.
intent.setType("image/*");
// intent.setType("video/*");
intent.setData(Uri.fromFile(dir));
// intent.setType("media/*");
// intent.
startActivityForResult(intent, 1);
}
else
{
showToast("No file exist to show");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (data==null) {
showToast("No image selected");
//finish();
}
else
{
Uri selectedImageUri = data.getData();
// String filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(selectedImageUri);
startActivity(intent);
}
else
{
showToast("Image path not correct");
}
}
}
}

Runtime Cropping an Image in android

I have already selected an image from SD card in my activity's ImageView using Intent.and now I want to show a fixed size moving Rectangle i.e. we have to use gesture and whatever portion of the image we want,then we are able to crop that.How can we do that?Its really tough for me to do?
Please help me in doing that?
Update-->I have been able to bring the rectangle and I m getting problem in cropping and saving that selected part.How to do this?
ok geetanjali. try this code this will open gallery and you can pick a photo to crop, it will store with name starts from apple, you can see cropped image in your activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop","true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 1);
}
private Uri getTempFile() {
if (isSDCARDMounted()) {
String f;
muri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"apple_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
//File f = new File(Environment.getExternalStorageDirectory(),"titus1.jpg");
try {
f=muri.getPath();
} catch (Exception e) {
}
return muri;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String filePath= muri.getPath();
Log.e("path", "filePath");
Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
image = (ImageView)findViewById(R.id.image);
image.setImageBitmap(selectedImage);
}
}
}

Categories

Resources