I'm getting Runtime Exception while getting Uri from Bitmap. BTW the same code works perfect in standalone project.
Call to Camera intent
private void openCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,
REQUEST_CODE_CAPTURE_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CAPTURE_IMAGE && resultCode == getActivity().RESULT_OK
&& null != data) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
String s = getImageUri(photo).toString();
Globals.saveImagePathToSharedPref(getActivity(), s);
setImage(Uri.parse(s));
}
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
In getImageUri method, the path is returning null, and the exception as follows:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,
request=327780, result=-1, data=Intent { act=inline-data (has extras) }}
to activity : java.lang.NullPointerException: uriString
You can use MediaStore.EXTRA_OUTPUT as an extra to the cameraIntent, the full sized image will then be saved to that location. The bitmap returned in the intent activity result is just a thumbnail.
You can use
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
To generate the Uri to pass in EXTRA_OUTPUT
Your getImageUri() method is poorly named, because it does more than get an Uri, it also saves the image to storage first (which is arguably the more important operation).
Look at the docs for MediaStore.Images.Media.insertImage(…):
Returns
The URL to the newly created image, or null if the image failed to be stored for any reason.
So that's (likely) the reason why you get a null path back and your code explodes.
There's nothing you can do to guarantee that saving the image always succeeds (e.g. the flash memory may be full), so you'll have to modify your code to recover from this error case, e.g. by telling the user that their image could not be saved.
Related
I'm trying to open the camera from my app and get a bitmap. But this doens't work. I got this error :
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: content:/media/external/images/media/9969: open failed: ENOENT (No such file or directory)
Here is the code :
private void openCamera()
{
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "New Picture");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "From the camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//Camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
}
When I call openCamera(), here is the activity result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode)
{
case RESULT_OK :
{
//imageView.setImageURI(image_uri); this works
Bitmap bitmap = null;
String photoPath = image_uri.toString();
bitmap = BitmapFactory.decodeFile(photoPath);
imageView.setImageBitmap(bitmap); //this doesnt work ! --> the bitmap is empty
}
//finish
case RESULT_CANCELED :
{
// finish();
}
default: {
//finish();
}
}
I need the bitmap to store the image after that.
It's pretty weird because the image is well saved into the gallery but I can't get it...
Ideally, you would be using Glide, Picasso, or another image-loading library, and simply have it load the image from the Uri into your ImageView.
If you insist upon using your basic approach, despite its poor performance, replace:
String photoPath = image_uri.toString();
bitmap = BitmapFactory.decodeFile(photoPath);
with:
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(image_uri));
A Uri is not a file.
Hi so i want to take a picture with camera intent but after taking the picture i get the following error:
ERROR:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {radautiul_civic.e_radauti/radautiul_civic.e_radauti.Civic_Alert}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5004)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5047)
at android.app.ActivityThread.access$1600(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at radautiul_civic.e_radauti.Civic_Alert.onActivityResult(Civic_Alert.java:86)
at android.app.Activity.dispatchActivityResult(Activity.java:7165)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5000)
Here is my code:
static final int REQUEST_TAKE_PHOTO = 1;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
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(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
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
And here is my StartActivityForResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
imgBitmap = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(imgBitmap);
Toast.makeText(getApplicationContext(),mCurrentPhotoPath,Toast.LENGTH_SHORT);
}
}
So this is what I did before error: 1.Opened my camera intent 2.Took the picture 3.I pressed OK and i got that the data from result is empty error
I followed this documentation from google: https://developer.android.com/training/camera/photobasics.html#TaskGallery
So can you guys tell me what i did wrong? Thanks in advance
If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method.
If you will check the path which you are passing then you will know that actual camera had written the captured file in that path.
So you need some changes in your code
To start the camera activity use
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
After capturing the image you will get captured image in the bitmap format in onActivityResult method. Now when you get the bitmap use it as you want to.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Bitmap bmp = intent.getExtras().get("data");
//Use the bitmap as you want to
}
}
Note: Here bitmap object consists of thumb image, it will not have a full resolution image
Some useful references
http://dharmendra4android.blogspot.in/2012/04/save-captured-image-to-applications.html
How to get camera result as a uri in data folder?
I've found a lot of answers for questions like mine but they doesn't make sense for me. Let me explain.
I have a ImageButton that let the user take a picture and display it on interface. When i try to get image URI, it returns null:
Uri uri = data.getData();
I've made some searches on internet and found solutions like:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
try {
if (resultCode == Activity.RESULT_OK) {
updateProfilePicure = Boolean.TRUE;
switch(requestCode){
case 0:
Bundle extras = data.getExtras();
Object xx = data.getData();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Uri tempUri = getImageUri(imageBitmap);
imageView.setImageBitmap(imageBitmap);
break;
default: break;
}
}
} catch(Exception e){
e.printStackTrace();
}
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(
ApplicationContext.getInstance().getContext().getContentResolver(), inImage,
"Title", null);
return Uri.parse(path);
}
For me, it doesn't make sense because when the call goes to method onActivityResult(), the picture is already saved on DCIM folder and don't have any reason to save it again. So why should i use it?
Is possible to find another way to retrieve the URI from captured image?
Thank's in advance.
the picture is already saved on DCIM folder and don't have any reason to save it again.
Not necessarily. Quoting the documentation for ACTION_IMAGE_CAPTURE:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field.
(the "extra field" here is an extra keyed as data)
The code snippet that you pasted is retrieving the data extra, and so the image is not stored anywhere.
Is possible to find another way to retrieve the URI from captured image?
You already have the code for this, in your first code snippet -- if you are specifying the Uri as EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE request, you will get a Uri back to the image that was taken in the Intent handed to onActivityResult().
I'm following along on this example:
http://developer.android.com/training/camera/photobasics.html
If you Ctrl-F for this putExtra(MediaStore.EXTRA_OUTPUT it'll take you to a segment of code I'm unsure of. Further up in the app, they override onActivityResult and try to pull the image from this intent out of the activity result to display in the app, but when I was doing this the Intent arg in onActivityResult was null. I tried changing my putExtra to take "data" instead of MediaStore.EXTRA_OUTPUT and suddenly it works perfectly.
Can anyone explain what this tutorial is trying to get me to do?
So basically, the code in question:
static final int REQUEST_IMAGE_CAPTURE = 1;
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(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
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
Intent data in onActivityResult is null, so it'd crash when i called getExtras. I changed dispatchTakePictureIntent to putExtra("data", Uri.fromFile(photoFile)); and it works.
I'm just confused if this is a blunder on Google's part and made a mistake in their tutorial, or if I did something wrong / don't understand? Only reason I thought to make this change is because it uses the string data when it calls extras.get("data"). So I don't even understand my solution :(
putExtra("NameOfExtra", object)
so they are getting an extra named "data" - the string is the NAME of the extra value that was previously put.
I am new at this :)
I am trying to load a picture from the sdcard into an ImageView in this way:
b_picture.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
Here I am trying to retrive the picture and change the ImageView:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
iv_picture.setImageBitmap(bm);
}
And I get this from the logcat:
Failure delivering result ResultInfo {who=null, request=0, result=-1,
data=Intent { dat=content://media/external/images/media/2
I can't solve this problem. Can you help me? Thanks.
The data associated with your returned Intent is not a bitmap. It's a URI you can use to look up in the MediaStore ContentProvider to get back the image you want. :)
You can find a mostly-working example over at this question.
Edit: To expand:
When you go off and query the MediaStore for an image, it isn't returning you the actual image. It's returning you a URI that you can use to look up the image. The way you translate that URI into an actual image is this:
Your URI is content://media/external/images/media/2 as per the error message.
So, we'll basically create a query and run it on the MediaStore's ContentProvider, which is a database of images. Pass that URI into this function:
public Bitmap loadFullImage( Context context, Uri photoUri ) {
Cursor photoCursor = null;
try {
// Attempt to fetch asset filename for image
// DATA is the column name in the database for the filename of the image
String[] projection = { MediaStore.Images.Media.DATA };
// use the URI you were given in order to look up the right image,
// and get a Cursor object that will iterate over the matching rows in the
// database.
photoCursor = context.getContentResolver().query( photoUri,
projection, null, null, null );
// since we only care about one image...
if ( photoCursor != null && photoCursor.getCount() == 1 ) {
// go to the first row that was returned
photoCursor.moveToFirst();
// get the string in the DATA column at that row
String photoFilePath = photoCursor.getString(
photoCursor.getColumnIndex(MediaStore.Images.Media.DATA) );
// Load image from path
return BitmapFactory.decodeFile( photoFilePath, null );
}
} finally {
// close up the cursor
if ( photoCursor != null ) {
photoCursor.close();
}
}
return null;
}
// path ex: /sdcard/myimage.png
String imageInSD = "Your image path here";
BitmapFactory.Options bOptions = new BitmapFactory.Options();
bOptions.inTempStorage = new byte[16*1024];
bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
imageView.setImageBitmap(bitmap);