I'm trying to display the path of a saved picture taken by the camera, by calling
`data.getdata`
inside a Toast, but the App crashs. I also tried data.getDataString but it did not solve
any thing.
Code:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "My Images");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "img01");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent,CAMERA_REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == CAMERA_REQUEST_CODE) && (resultCode == RESULT_OK)) {
Toast.makeText(getApplicationContext(), "Image Saved To: "+data.getData(), Toast.LENGTH_SHORT).show();
}
Camera Intent result woes
looked through this..
have you tried data.getExtras().get(TAG); ?
Get the extras bundle from your intent, there is the resulting data accessible.
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Don't forget a null check, since I'm in the impression that the tag "data" is not valid on all phones.
edit: Made code more precise, i.e. giving the exact solution here.
Also use, data.getData().toString()
data.getData().toString() should work. But, it won't actually give you the actual path of the image stored. It'll rather give you an URI of that image. You'll need to parse that uri using.
public String getRealPathFromURI(String uriString) {
try {
String[] proj = { MediaStore.Image.Media.DATA};
Log.d("First", proj[0]);
Cursor cursor = managedQuery(Uri.parse(uriString), proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Image.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Alas!";
}
Related
I am trying to get the Path from an image to send it later to a server. The problem is when I try to get it, my code doesn't work (you will see there is an extra }. That is because the code from the OnCreate ends and then I worte the other functions):
enviar.setOnClickListener(new View.OnClickListener() {
String datos="";
//Bundle extras=getIntent().getExtras();
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
//Uri imagen=intent.getData();
//datos=imagen.getPath();
//mostrar.setText(datos);
}
});
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == this.RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
String path = getRealPathFromURI(imageUri);
mostrar.setText(path);
}
catch (Exception e) {
Log.e("Erroreeeee: ", e.getMessage());
}
}
break;
}
}
You have two problems.
The first one is that startActivityForResult() is not immediate. You do not have any results in the next statement.
So, you are welcome to call startActivityForResult(), as I do in this sample app:
private void get() {
Intent i=
new Intent()
.setType("image/png")
.setAction(Intent.ACTION_GET_CONTENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_GET);
}
Your results are delivered to onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode==Activity.RESULT_OK) {
Uri image=resultData.getData();
// do something
}
}
Your second problem is that you are thinking that you are picking a file. You are not. You are picking a piece of content, using any activity that the user decides to have handle ACTION_GET_CONTENT. getPath() only has meaning if the scheme of the Uri is file, and that is rather unlikely. There is no reliable means of getting a filesystem path for an arbitrary Uri, for the simple reason that the Uri does not have to point to a file.
Ideally, your "upload to a server" logic can work with an InputStream. In that case, call openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. If your "upload to a server" logic only works with files, use that InputStream to copy the content to some temporary file that you control (e.g., in getCacheDir()), then use that temporary file for your upload. Delete the temporary file when you are done with it.
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?
In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, RETURN_FILE_PATH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//data is always null here.
//requestCode = RETURN_FILE_PATH;
//resultCode = Activity.RESULT_OK;
}
I checked the values for file and output Uri, both are fine and the captured image actually exists at that location.
But the data returned in onActivityResult is always null even after capturing the image.
EDIT:
I checked this question:
onActivityResult returns with data = null
which says:
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
and maybe that solution will work for me. But the above code of mine was a working code until now for the same scenario.
According to this post data is null when you pre insert a uri. That means you already defined your output uri here:
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
So when you get a Activity.RESULT_OK; just load the taken photo by its known url.
Try this code this is working for me.
else if(requestCode == Constant.PICK_FROM_CAMERA)
{
if (resultCode == Activity.RESULT_OK)
{
if(data!=null)
{
mImageCaptureUri = data.getData();
//path= mImageCaptureUri.getPath();
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
else
{
file1 = new File(Environment.getExternalStorageDirectory(),
String.valueOf(System.currentTimeMillis()) + "_FromCamera.jpg");
Uri mImageCaptureUri = Uri.fromFile(file1);
try
{
path = getPath(mImageCaptureUri,Wonderlistpage.this); //from Gallery
}
catch(Exception e)
{
path = mImageCaptureUri.getPath();
Log.i("check image attach or not", e.toString());
}
String arr[] = path.split("/");
int i;
String k = null;
for(i=0;i<arr.length;i++)
{
k=arr[i];
}
photoname="_"+String.valueOf(System.currentTimeMillis()) +k;
if(setprofileimage_sendimagewithmessage==1)
{
performCrop(mImageCaptureUri);
}
else
{
loading_details="CAMERA";
new performBackgroundTask33().execute();
}
}
//new UploadTask().execute();
}
}
Try following code
{
final String[] imageColumns = { MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (fullPath.contains("DCIM")) {
//get bitmap from fullpath here.
return;
}
}
while (imageCursor.moveToNext());
Just Put this code into your onActivityResult. The same problem i have faced on some devices and this solved my problem. Hope this will also help you.
try {
Uri selectedImage = output;
if (selectedImage == null)
return;
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();
} catch (Exception e) {
return;
}
You will get the Picture path in picturePath variable and Uri in selectedImage Variable.
If your activity has launchmode as singleInstance in your manifest then you would face this issue. Try changing it. As it cancels the result everytime.
Hi every one in the below code after the image has been selected it is not moving to next activity ,in gallery if we select first item it remains in the same activity but we select another item other than first position image it is moving to next activity
startActivity(mv); the shown startactvity is not calling when we click on the first position image
but the toast is appearing as image has been selected but not moving to next activty
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
case R.id.imageView2:
upLoadPhoto();
break;
protected void upLoadPhoto() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && data != null && data.getData() != null) {
System.out.println("in case");
Uri _uri = data.getData();
if (_uri != null) {
// User had pick an image.
Cursor cursor = getContentResolver()
.query(_uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
Log.v("imageFilePath", imageFilePath);
File photos = new File(imageFilePath);
try {
gbmp = BitmapFactory.decodeStream(
new FileInputStream(photos), null, null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cursor.close();
}
mv = new Intent(Imageselection.this, Modeselection.class);
mv.putExtra("test", gbmp);
mv.putExtra("name", 100);
System.out.println("going to gamestart class");
startActivity(mv);
Toast.makeText(getApplicationContext(), "Image selected", Toast.LENGTH_SHORT).show();
}
Its because you passed the whole image to the bundle.
The bundle has limited Size, you cannnot put the image itself into the intent.
You need to save your image to a cache, then either pass the image's file name or file path to the putExtra and then retrieve it later by accessing the filename or file path.
For your case, you select an image from gallery, then you can get the URI or path of that image, put the URI/path to the intent, and retrieve it on your another activity.
When you call an intent to launch the gallery, it will return with data which contains the selected file's Uri.
Here r some sample code you may need if you launch the default gallery:
// Launch Gallery to choose pic.
Intent intentLaunchGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentLaunchGallery, LOAD_IMAGE_ACTIVITY_REQUEST_CODE);
...
private String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
...
// Gallery launched to choose picture
if (requestCode == LOAD_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
filePath = getPath(fileUri);
// fileUri = Uri.parse(filePath);
// call media scanner to refresh gallery
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{filePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("MediaScanner", "Scanned " + path + ":");
Log.i("MediaScanner", "-> uri=" + uri);
}
});
// Toast.makeText(this, "Image chosen from: " + filePath, Toast.LENGTH_LONG).show();
Log.d("MainMenu->onActivityResult", "Image chosen from: " + filePath);
// display the picture chosen by user
Intent intentShowMarkers = new Intent(MainMenuActivity.this, ShowMarkersActivity.class);
intentShowMarkers.putExtra("IMG", filePath);
intentShowMarkers.putExtra("FLAG", false);
MainMenuActivity.this.startActivity(intentShowMarkers);
} else if (resultCode == RESULT_CANCELED) {
// user pressed the cancel of gallery
Toast.makeText(MainMenuActivity.this, "Cancelled.", Toast.LENGTH_SHORT).show();
}
}
try below code. for select an image from gallary
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]);
filePath = cursor.getString(columnIndex);
cursor.close();
and in your onActivityResult method write below intent to go for next activity
Intent picIntent = new Intent(CurrentActivity.this,
NextActivity.class);
picIntent.putExtra("gallery", filePath);
startActivity(picIntent);
in your NextActivity class onCreate Method write below code
ImageView imageView = (ImageView)findViewById(R.id.imgView);
String fileString = getIntent().getStringExtra("gallery");
imageView.setImageBitmap(BitmapFactory.decodeFile(fileString));