This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to fetch a clicked image from the folder fizzzzz and display it in the listview but the cursor is giving null pointer exception.I am new to android. Please help me out.
// take a photo
private void activeTakePhoto() {
final Dialog dialog = new Dialog(this);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
int MEDIA_TYPE_IMAGE = 1;
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
try {
FileOutputStream outputStream_image = openFileOutput(file_image, MODE_WORLD_READABLE);
outputStream_image.write(string.getBytes());
outputStream_image.close();
Toast.makeText(getBaseContext(), "location of image saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private Uri getOutputMediaFileUri(int MEDIA_TYPE_IMAGE) {
// TODO Auto-generated method stub
if(isExternalStorageWritable()) {
Toast.makeText(getBaseContext(),"Verifying SD card",Toast.LENGTH_SHORT).show();
return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
}
return null;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private 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_DCIM), "Fizzzzzzz");
// 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");
Toast.makeText(getBaseContext(),"File directory creation failed",Toast.LENGTH_LONG).show();
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
int MEDIA_TYPE_IMAGE = 1;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
Toast.makeText(getBaseContext(),"Created file name",Toast.LENGTH_LONG).show();
} else {
return null;
}
return mediaFile;
}
//onActivityResult
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
final Dialog dialog= new Dialog(this);
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
managedQuery(fileUri, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA); //NullPointerException here.
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle(fname);
image.setDescription(" ");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
daOdb.addImage(image);
adapter.notifyDataSetChanged();
// listView.invalidateViews();
dialog.cancel();
}
}
}
managedQuery() is a wrapper for ContentResolver#query() and it can return null. You'll need to check for cursor != null before trying to call any method on it.
Related
Those are variables
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
// the same for Android 5.0 methods only
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
This is the file chooser code
Usually it should create a image after taking the image, but it is creating a blank image before opening the camera intent, and then it is showing an error icon instead of showing the Image.
Please help me to fix the problem
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// creating image files (Lollipop only)
private File createImageFile() throws IOException {
// Create an image file name
Log.d(TAG, "createImageFile: creating Image");
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
mCameraPhotoPath = "file:" + image.getAbsolutePath();
return image;enter code here
}
On Activity Result code given below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
// start of code for Lollipop only
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
Remove this
return File.createTempFile(imageFileName,".jpg",storageDir);
Add this
File image = new File(storageDir.toString()+"/"+imageFileName+".jpg");
return image;
No exercise needed you came here for an answer i presume.
In the MainActivity I take a picture from camera as the official documentation show:
private void dispatchTakePictureIntent() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CAMERA);
} else {
if (Build.VERSION.SDK_INT >= 24) {
try {
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
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) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 2);
}
}
}
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 = getExternalFilesDir(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;
}
Then I save the photo to the gallery:
private Uri galleryAddPic() {
try{
file = new File(mCurrentPhotoPath);
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), null);
this.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.v("UriTaken", Uri.fromFile(file).toString());
return Uri.fromFile(file);
}
Then, with putExtra, I pass to the next activity the Uri of the file.
The uri is this:
file:///storage/emulated/0/Android/data/com.my.name.myappname/files/Pictures/JPEG_20181231_002549_9133887087473873179.jpg
In the new activity, I retrieve the uri, and before I set the imageview with it(if I use image.setImageURI(imageUri); it works), I want to rotate the image to the exact orientation(I don't know why in the image view is always rotated).
I use this code:
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("uri"));
path = getPath(imageUri);
try {
//filePath = getFileName(path);
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bitmap = BitmapFactory.decodeFile(path);
Bitmap rotatedBitmap = null;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
image.setImageBitmap(rotatedBitmap);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
image.setImageBitmap(rotatedBitmap);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
image.setImageBitmap(rotatedBitmap);
break;
case ExifInterface.ORIENTATION_NORMAL:
image.setImageBitmap(bitmap);
default:
rotatedBitmap = bitmap;
image.setImageBitmap(rotatedBitmap);
}
} catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
And here the method that cause the crash:
public String getPath(Uri imageUri) {
String wholeId = DocumentsContract.getDocumentId(imageUri);
String id = wholeId.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
On the first line of the method I got the error posted above, invalid uri: file///storage........etc
If I get the picture from gallery it works, because i get this Uri:
content://com.android.providers.media.documents/document/image%3A97897
I don't know if the problem is in the method that saves the image in the MainActivity or is in the getPath() method. What I need to do is to take a picture, save to the gallery and retrieve in the next activity.
So after trying many answers for the same question, here are just two e.g;
Saving an image in android
and
Saving an image to a server using a Java applet
My app still fails in fact whatever I have done has made it worse, before it would actually save the image as "temp.jpg" in the ExtSD root folder, now when I click the tick to accept the photo nothing happens, no crashing, no nothing, I can retake the image and I can cancel the taking of a photo but nothing else happens.
What it does now:
Opens the camera (or gallery)
Takes the photo
Fails to save/set the photo
What I want it to do;
Take the photo
Store it with a unique name (timestamp)
Have the image set to CircleView
Here is my code (if you need more please ask for what you need);
CircleImageView circleImageView;
ImageButton b;
private void selectImage() {
final CharSequence[] options = { "Take a Pic", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Profile Pic");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take a Pic"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String folder_main = "iDealer";
String sub_folder = "ProPics";
String timeStamp = new SimpleDateFormat("ddMMyyy_HHmmss").format(Calendar.getInstance().getTime());
String pro_pic_name = folder_main + "_" + timeStamp;
File f = new File(android.os.Environment.getExternalStorageDirectory() + "/" + folder_main + "/" + sub_folder + pro_pic_name);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
circleImageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
circleImageView.setImageBitmap(thumbnail);
}
}
}
I am developing an Android app in which the user can select a picture from the gallery or can click a photo through the phone's camera and save in the app's folder called FiZZ. The camera part of app runs perfectly fine on all android phones except Samsung.The code given below throws a NullPointerException at image.setPath(fileUri.getPath()); and crashes.
MainActivity.java:
Below is how I take a photo and save it in /DCIM/FiZZ folder:
/**
* take a photo
*/
private void activeTakePhoto() {
final Dialog dialog = new Dialog(MainActivity.this);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
int MEDIA_TYPE_IMAGE = 1;
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
try {
FileOutputStream outputStream_image = openFileOutput(file_image, MODE_WORLD_READABLE);
outputStream_image.write(string.getBytes());
outputStream_image.close();
Toast.makeText(getBaseContext(), "location of image saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private Uri getOutputMediaFileUri(int MEDIA_TYPE_IMAGE) {
// TODO Auto-generated method stub
if(isExternalStorageWritable()) {
//Toast.makeText(getBaseContext(), "value: "+ Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE)), Toast.LENGTH_LONG).show();
return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
}
else
return null;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private 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_DCIM), "FiZZ");
// 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("FiZZ", "failed to create directory");
Toast.makeText(getBaseContext(),"File directory creation failed",Toast.LENGTH_LONG).show();
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
int MEDIA_TYPE_IMAGE = 1;
if (type == MEDIA_TYPE_IMAGE){
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname= "IMG_"+ timeStamp + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
The request_image_capture case is called:
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String filePath = imageFile.getAbsolutePath();
String imageName = String.valueOf(mediaFile);
Cursor cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.MediaColumns._ID);
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle(imageName);
image.setDescription(" ");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
image.setName(null);
image.setPriority("OFF");
images.add(image);
daOdb.addImage(image);
adapter.notifyDataSetChanged();
cursor.close();
} else {
MyImage image = new MyImage();
image.setTitle(imageName);
image.setDescription(" ");
image.setDatetime(System.currentTimeMillis());
image.setPath(fileUri.getPath());//NullPointerException
image.setName(null);
image.setPriority("OFF");
images.add(image);
daOdb.addImage(image);
adapter.notifyDataSetChanged();
//swipelist.invalidateViews();
}
}
I am using following code to take images from camera or Other intents. On mY Samsung S2 It works fine but HTC Is giving error
private void openImageIntent()
{
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "OpenionDroid" + File.separator);
root.mkdirs();
final String fname = UUID.randomUUID().toString();
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam)
{
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, Constants.IMAGE_REQUEST_CODE);
}
#SuppressWarnings("static-access")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == mContext.RESULT_OK)
{
if(requestCode == Constants.IMAGE_REQUEST_CODE)
{
final boolean isCamera;
if(data == null)
{
isCamera = true;
}
else
{
final String action = data.getAction();
if(action == null)
{
isCamera = false;
}
else
{
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera)
selectedImageUri = outputFileUri;
else
selectedImageUri = data == null ? null : data.getData();
if (isPhoto1Selected)
{
photo1Uri = selectedImageUri;
try {
Bitmap bitmap = Utilities.decodeSampledBitmap(Utilities.readBytes(selectedImageUri, mContext), 100, 100);
myQuestion.setLeftThumbnail(Utilities.decodeBitmapToArray(bitmap));
photo1.setImageBitmap(bitmap);
} catch (IOException e) {
Utilities.displayAlert("Oops!", e.getMessage(), mContext);
e.printStackTrace();
}
}
else
{
photo2Uri = selectedImageUri;
try {
Bitmap bitmap = Utilities.decodeSampledBitmap(Utilities.readBytes(selectedImageUri, mContext), 100, 100)
;
myQuestion.setRightThumbnail(Utilities.decodeBitmapToArray(bitmap));
photo2.setImageBitmap(bitmap);
} catch (IOException e) {
Utilities.displayAlert("Oops!", e.getMessage(), mContext);
e.printStackTrace();
}
}
}
}
}
In my code S2 Enters in this
if(data == null)
{
isCamera = true;
}
While HTC goes here
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
The result isCamera is false. so it tries to run
selectedImageUri = data == null ? null : data.getData();
which gives null
What could be solution, how can i retrieve image from camera?
For HTC Desire, you need some special handling for taking pictures. Here is some code, you will have to adapt it to your needs :
protected static Uri createUriFromPhotoIntentForHtcDesireHD( Activity activity, Intent intent, Uri uri ) {
FileOutputStream fos = null;
try {
Bitmap bitmap = (Bitmap) intent.getExtras().get( "data" );
File outputDir = activity.getCacheDir();
File outputFile = File.createTempFile( "Photo-", ".jpg", outputDir );
fos = new FileOutputStream( outputFile );
bitmap.compress( Bitmap.CompressFormat.JPEG, 90, fos );
uri = Uri.fromFile( outputFile );
} catch ( IOException e ) {
Ln.e( e, "Error creating temp file for HTC Desire HD" );
} finally {
try {
if ( fos != null ) {
fos.close();
}
} catch ( IOException e ) {
Ln.e( e, "Error closing temp file for HTC Desire HD" );
}
}
return uri;
}
If you start an activity to take picture, then in you onActivityResult method, you would expect an intent to contain the uri of the file to download. If it doesn't, then use this code :
Uri uri = intent.getData();
// HTC Desire Bug
if ( uri == null && intent.getExtras() != null && intent.getExtras().get( "data" ) instanceof Bitmap ) {
uri = createUriFromPhotoIntentForHtcDesireHD( activity, intent, uri );
Ln.d( "The intent is %s", intent.getExtras().get( "data" ).getClass().getName() );
}