what is the reason of this error :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.sqlfirst.AddImage}: java.lang.NullPointerException: uriString
the error is pointing at this line where I am receiving the intent
img.setImageURI(Uri.parse(imagePath ));
I am trying to send a sd card path through an intent to another acitivity and convert it into an image
this is the code:
Here sending the path of the image in sd card
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
// startActivityForResult(
// Intent.createChooser(intent, "Complete action using"),2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Bundle extras2 = data.getExtras();
filePath = data.getData();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("imagepath", filePath);
startActivity(i);
here I suppose to recieve the path of the image and decrease the size of the image.
String imagePath = getIntent().getStringExtra("imagePath");
ImageView img=(ImageView) findViewById(R.id.imageView);
img.setImageURI(Uri.parse(imagePath ));
Bitmap bitmap = ((BitmapDrawable)img.getDrawable()).getBitmap();
Bitmap out = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
// bitmap is the image
ByteArrayOutputStream stream = new ByteArrayOutputStream();
out.compress(Bitmap.CompressFormat.JPEG, 60, stream);
bitmap.recycle();
To use the path correctly you should first create it to have somewhere to store it, you can use that and later on delete it or use the data from the result you got.
Here is the code to create a Uri, pass it to your Intent. Once you get the result you can pass the Uri to another class by using getPath from the Uri package.
/**
* Creating file uri to store image/video
*/
public static Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
/**
* returning image / video
*/
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"YOUR DIRECTORY NAME");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("image upload", "Oops! Failed create "
+ "YOUR DIRECTORY NAME" + " directory");
return null;
}
}
//TODO change naming
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
EDIT 1:
To convert a file to a bitmap you can use this code, provided by #Nikhilreddy Gujjula in this question
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
You are setting imagepath as an extra and trying to retrieve imagePath.
Also note that setImageURI() is not a good choice, as it will load and decode the image on the main application thread. Use an image-loading library, like Picasso or Universal Image Loader.
Related
I know it seems like a very basic question, but it's specifically for Android Q.
I just want to get an image from Gallery and compress it and send to the server. But because of the Android Q's Scoped Storage, it's harder than I thought. I'll first explain what I did with code:
First I send out the intent to pick the image.
fun openGallery(fragment: Fragment){
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "*/*"
val mimeTypes = arrayOf("image/*")
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
fragment.startActivityForResult(intent, REQUEST_IMAGE_PICK)
}
It works fine, and I'm able to get the image in the onActivityResult method
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_PICK && resultCode == Activity.RESULT_OK && null != data) {
val selectedImage = data.data
val source = ImageDecoder.createSource(activity!!.contentResolver, selectedImage)
val bitmap = ImageDecoder.decodeBitmap(source)
mBinding.circularProfileImage.setImageBitmap(bitmap)
}
}
Okay now the question is how can I access this image in File format, so I can further process/compress it.
Following things I've tried:
val mImagePath = getImagePathFromUri(activity!!, selectedImage)
This is the path I've got:
/storage/emulated/0/DCIM/Camera/IMG_20191022_152437.jpg
I created a file from it, in the following way:
val file = File(mImagePath)
And Following is my custom logic to compress and upload image:
val mNewFile = MediaCompressor.compressCapturedImage(activity!!, file, "ProfilePictures")
uploadProfile(mNewFile)
In this custom logic, I have a method to handle sampling and rotation of the image as follows:
fun handleSamplingAndRotationBitmap(context: Context, selectedImage: File, reqWidth: Int, reqHeight: Int): Bitmap {
val mUri = Uri.fromFile(selectedImage)
// First decode with inJustDecodeBounds=true to check dimensions
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
var imageStream = context.contentResolver.openInputStream(mUri)
BitmapFactory.decodeStream(imageStream, null, options)
imageStream!!.close()
// Calculate inSampleSize
options.inSampleSize =
calculateInSampleSize(options, reqWidth, reqHeight)
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false
imageStream = context.contentResolver.openInputStream(mUri)
var img = BitmapFactory.decodeStream(imageStream, null, options)
img = rotateImageIfRequired(context, img!!, mUri)
return img
}
But when I'm trying to open the stream using context.contentResolver.openInputStream
I get the following error:
java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20191022_152437.jpg: open failed: EACCES (Permission denied)
I know I'm getting this because in Android 10 we don't have the permission to directly access files from external storage.
So, please help me figure this out, how can I use the image from external storage as a file in Android 10.
Note: I've all the required permissions, so that's not the issue
Following things I've tried:
There is no possible reliable getImagePathFromUri() implementation.
In this custom logic, I have a method to handle sampling and rotation of the image as follows:
You do not need a File in that function. After all, your very first statement in that function goes and creates a Uri from that File. So, replace the File parameter with the Uri that you have, and skip the Uri.fromFile() call.
how can I use the image from external storage as a file in Android 10.
You can't. And, as demonstrated above, you do not need it for what you are doing.
If you find yourself in some situation where you are stuck using some library or API that absolutely positively must have a File:
Open an InputStream on the content, using contentResolver.openInputStream(), as you are doing today
Copy the bytes from that InputStream to some FileOutputStream on a file that you can read/write (e.g., getCacheDir() on Context)
Use your copy with the library or API that requires a File
Create a Directory for data to be stored in Android/data/package name by:
private void createDir() {
String timeStamp = utils.currentTimeStamp();
File storageDir = getExternalFilesDir(null);
File image;
try {
image = File.createTempFile(timeStamp, ".png", storageDir);
Log.i("SANJAY ", "createDir: " + image.getPath());
} catch (IOException e) {
e.printStackTrace();
Log.i("SANJAY ", "createDir: " + e.getMessage());
}
}
now call the gallery intent:
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, 100);
In onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 100) {
Uri mediaUri = data.getData();
//display the image
try {
InputStream inputStream = getBaseContext().getContentResolver().openInputStream(mediaUri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byteArray = stream.toByteArray();
bind.photo.setImageBitmap(bm);
//Log.i("SANJAY ", "onActivityResult: " + saveBitMap(this, bm));
uri = Uri.fromFile(saveBitMap(this, bm));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
the get the Uri from File using this method:
private File saveBitMap(Context context, Bitmap Final_bitmap) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/"/*Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ""*/);
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if (!isDirectoryCreated)
Log.i("SANJAY ", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + ".jpg";
File pictureFile = new File(filename);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
Final_bitmap.compress(Bitmap.CompressFormat.PNG, 18, oStream);
oStream.flush();
oStream.close();
Log.i("SANJAY ", "saveBitMap :: Save Image Successfully..");
} catch (IOException e) {
e.printStackTrace();
Log.i("SANJAY", "There was an issue saving the image.");
Log.i("SANJAY", "Error :: " + e.getLocalizedMessage());
}
return pictureFile;
}
I am having a problem while trying to save a photo to storage with an Android app. The app uses the devices camera to take a photo and save it as a PNG to the device.
For some reason no matter what I do or where I store the image the quality is very poor. The app is an existing project that is quite large so I was wondering if there are other factors to consider when saving images to a device or maybe another way of overriding the quality.
This is the function that was coded by the previous dev:
public String saveImageToDevice(Bitmap image) {
saveCanvasImage(image);
String root = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.app.android";
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = "Image-"+ timeStamp +".png";
File file = new File (myDir, fname);
if (file.exists ()){
file.delete ();
}
try {
Toast.makeText(getActivity(), "Saving Image...", Toast.LENGTH_SHORT).show();
Log.i("Image saved", root+"/saved_images/"+fname);
FileOutputStream out = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, out);
imageLocations.add(fname);
out.flush();
out.close();
//return myDir.getAbsolutePath() + "/" +fname;
return fname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
And this is a function I have tried myself from an example online:
public void saveCanvasImage(Bitmap b) {
File f = new File(Environment.getExternalStorageDirectory().toString() + "/img.png");
try {
f.createNewFile(); // your mistake was at here
FileOutputStream fos = new FileOutputStream(f);
b.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
Both of these produce the same very poor images. I have posted a before and after segment below.
This is what the camera preview looks like.
This is the resulting image once it has saved.
After speaking to a few people i am including my camera intent code:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
// Define the file-name to save photo taken by Camera activity
String fileName = "Camera_Example.png";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
#SuppressWarnings("unused")
Uri imageUri = getActivity().getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
//intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
As you can see the EXTRA_OUTPUT line is has been commented out due to it causing crashes with the below error:
12-17 13:31:37.339: E/AndroidRuntime(16123): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {}: java.lang.NullPointerException
I have also included my onActivityresult code too:
public void onActivityResult( int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
Bitmap bp = (Bitmap) data.getExtras().get("data");
//add the image to the note through a function call
note.addImage(bp);
note.saveImageToDevice(bp);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
OK so after a lot of help from MelquiadesI have eventually solved this issue. The problem I had was that my intent and onActivityResult were retrieving the thumbnail of the image and scaling it up (hence the poor quality).
The line below is responsible for getting the thumbnail preview (120px x 160px):
Bitmap bp = (Bitmap) data.getExtras().get("data");
In order to access the full image I need to add EXTRA_OUTPUT to the intent which looks as follows:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
I also declared my imageFilePath as a string at the top of my activity:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";
I then had to change onActivityResult so it could access the full image to use:
public void onActivityResult( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
//add the image to the note through a function call
note.addImage(rotatedBitmap);
note.saveImageToDevice(rotatedBitmap);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
The key part here is:
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
This code decodes the image you saved at imageFilePath into a usable bitmap. From here you can use it as normal.
Sometimes (apparently this is quite common) the image comes in rotated by 90°, the next bit of code will rotate that back if you need it to:
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
I got this code (from android web) that stores make a file location to store the image once started the activity
{
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */ private static
Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */ private static
File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
then i start my activity like this:
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
and then when i get the result on:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... }
i saw that debugging it, "data" is null..
I did the same thing but without adding the
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
and when i add no extra i recieve data info..
guess i have something wrong on writing/reading?? but how? i copyed from the android web!!
I do have permision camera writing reading external storage!
Help!!!!!!!!!!!!!!!
When you specify MediaStore.EXTRA_OUTPUT flag for your intent, the taken picture will be stored in your phone storage and no data will be returned.
from Docs:
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. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.
When you use the approach to store taken picture, you have to pass URI together with the intent to tell where to store taken picture
NightCrawler Gave a link on how to get data back onActivityResult
Copying the most important portion:
YourActivity extends Activity{
onCreate{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
onActivityResult(parameters..) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
yourImageView.setImageBitmap(photo);
}
}
}
I have implemented a code to save the captured video to a custom location.
// Constants
final static int REQUEST_VIDEO_CAPTURED = 1;
String CAPTURE_TITLE="MyVideo.3gp";
// Specified the desired location here
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM", CAPTURE_TITLE);
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
Now On Activity result I m getting the default path only and not the desired path where i intent to save the video.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
Uri capturedImageUri = data.getData();
Toast.makeText(this, capturedImageUri .getPath(), TOAST.LENGTH_LONG).show();
}
}
Now I dont know why it is not saving it to desired location similar thing I did try with Image capture and it worked.
Also I have added the desired permissions.
Any thoughts!!
try this instead...
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)), CAPTURE_TITLE);
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM", CAPTURE_TITLE);
Change To:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", CAPTURE_TITLE);
In my app, I have to capture a photo from the native camera app and then store it in my desired folder and then show that captured image in a new Activity. My code so far
To start native camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
My other methods
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/**Create a file for saving an image*/
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "KidzPuzzle");
//Create a storage directory if it does not exist
if(! mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("KidzPuzzle", "Failed to create directory");
return null;
}
}
//Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if(type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg" );
return mediaFile;
}else{
return null;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
if(resultCode == RESULT_OK){
//Image created and saved successfully to the specified fileUri
//Toast.makeText(this, "Image saved to : \n"+data.getDataString(), Toast.LENGTH_LONG).show();
String filePath = ((Uri) data.getExtras().get(MediaStore.EXTRA_OUTPUT)).toString();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
startActivity(new Intent(this, SplitImageActivity.class).putExtra("image", bitmap));
}else if(resultCode == RESULT_CANCELED){
//user canceled the captured image
}else{
//Image capture failed
}
}
}
The intent variable data in onActivityResult is always null. Please help me where I am going wrong.
NOTE: When I debug it, the control always satisfies the RESULT_OK condition and the shows NullPointerException, because of the value of data.
And another thing, if I am not using
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this code before starting the native camera, then data is not null.
please help me.
Chandra Sekhar,
as you have mentioned in the last that when you don't specify location for the image then data is not null so AFAIK it clearly indicates that when you pass location then it will return null and you will receive your image at your location. So you need to store that location separately and use that to access image when you get RESULT_OK.