Android image resize after camera intent callback - java

my first question here! I have a problem with a piece of code that starts a camera intent with the extra output options and then on activity result tries to resize that image. what is happening is that a nullpointer exception gets thrown in the resize function at the callback.
The original large picture is still saved on the file system, as I can access that from the filesystem.
The original camera jpeg is 2560x1920 in size and the phone in use is a google nexus one.
I have no clear idea asto why the resize is not working, anyone have any insight?
Here's some code:
The takePicture function that also creates the dummy file:
public boolean takePicture( ) {
Log.e(TAG, "takePicture interface function");
String FileUri = Environment.getExternalStorageDirectory() + "/samples/";
File file = new File(FileUri,"picture"+ pictureNumber +".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e(TAG, "intent started");
return true;
}
The on activity result callback function:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle the camera request returns and handle back button in camera.
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_CANCELED ) {
Toast toast = Toast.makeText(this,"Canceled, no picture taken.", 1000);
toast.show();
return;
}
else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK ) {
Log.e(TAG, "Camera intent return");
Bitmap scaledphoto = null;
int height = 300;
int width = 300;
Bitmap photo = BitmapFactory.decodeFile( APP_DATA_PATH + "/samples/picture" + pictureNumber + ".jpg" );
Log.e(TAG, "Picture fetched");
scaledphoto = Bitmap.createScaledBitmap(photo, height, width, true);
Log.e(TAG, "Picture scaled");
saveImageToFile(scaledphoto, "picture" + pictureNumber + ".jpg");
Log.e(TAG, "Scaled picture saved");
myWebView.loadUrl("javascript:pictureTaken(\""+ pictureLoc + "\")");
pictureNumber++;
And here's the LogCat:
06-21 14:59:13.496: E/AndroidRuntime(6130): FATAL EXCEPTION: main
06-21 14:59:13.496: E/AndroidRuntime(6130): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {test.test/test.test.CameraIntentTestActivity}: java.lang.NullPointerException
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.deliverResults(ActivityThread.java:2980)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3023)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.access$1100(ActivityThread.java:123)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1177)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.os.Handler.dispatchMessage(Handler.java:99)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.os.Looper.loop(Looper.java:137)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-21 14:59:13.496: E/AndroidRuntime(6130): at java.lang.reflect.Method.invokeNative(Native Method)
06-21 14:59:13.496: E/AndroidRuntime(6130): at java.lang.reflect.Method.invoke(Method.java:511)
06-21 14:59:13.496: E/AndroidRuntime(6130): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-21 14:59:13.496: E/AndroidRuntime(6130): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-21 14:59:13.496: E/AndroidRuntime(6130): at dalvik.system.NativeStart.main(Native Method)
06-21 14:59:13.496: E/AndroidRuntime(6130): Caused by: java.lang.NullPointerException
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:432)

Change
Bitmap photo = BitmapFactory.decodeFile( APP_DATA_PATH + "/samples/picture" + pictureNumber + ".jpg" );
To
Bitmap photo = (Bitmap) data.getExtras().get("data");

Related

How do I solve IabHelper Error

I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}

Camera intent crashing my application after few pictures

I am having a problem with some phones during coming back from android.provider.MediaStore.ACTION_IMAGE_CAPTURE. On HTC and Alcatel it works great, but on LG it crashes my application. I can save some pictures and after that my application crashes with Sorry! MyApplication has stoped. I have tried many ways how to avoid this but i still get the same error.
First i was using this
1: attempt
Taking picture with image path (not getting any exception):
public static void saveImage(String saveImgDir, String image, int TAKE_PHOTO_CODE, Activity activity) {
try {
GlobalVariables.incorrectButtonPressed = false;
// CREATE DIR IF NOT EXISTS
File directory = new File(saveImgDir);
directory.mkdirs();
// CREATE AND SAVE IMG
File imageFile = new File(saveImgDir + File.separator + image);
try {
imageFile.createNewFile();
} catch (IOException e) {
Log.d("IMG", "FILE CREATE: " + e.toString(), e.getCause());
}
Uri outputFileUri = Uri.fromFile(imageFile);
// CALL CAMERA ACTIVITY
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
activity.startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
} catch (Exception ex) {
Log.d("CAMPROBLEM", "bblockScenario", ex);
}
}
On activity result (not getting any exception):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == B_TAKE_PHOTO_CODE_AFTER && resultCode == RESULT_OK) {
Log.d("CAMPROBLEM", "ACTIVITY RESULT B_TAKE_PHOTO_CODE_AFTER RESULT OK");
imageTakenAfter++;
Toast.makeText(context, "PCITURE SAVED", Toast.LENGTH_LONG).
return;
}
if (requestCode == B_TAKE_PHOTO_CODE_AFTER && resultCode != RESULT_OK) {
Log.d("CAMPROBLEM", "ACTIVITY RESULT B_TAKE_PHOTO_CODE_AFTER RESULT NOT OK");
Toast.makeText(context, "PCITURE NOT SAVED", Toast.LENGTH_LONG).show();
return;
}
} catch (Exception ex) {
Log.d("CAMPROBLEM", "bblockScenario", ex);
}
}
2: attempt
Then i tried using async tasks (just to make sure that is not a memory leak). I called The saveImage function from AsyncTask class and still got the same problem. (not getting any eceptions)
3: attempt
Calling the intent without the image save path:
public static void saveImage(int TAKE_PHOTO_CODE, Activity activity) {
try {
GlobalVariables.incorrectButtonPressed = false;
// CREATE DIR IF NOT EXISTS
Intent it = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(it, TAKE_PHOTO_CODE);
} catch (Exception ex) {
Log.d("CAMPROBLEM", "bblockScenario", ex);
}
}
And saving my picture in my onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
String image = ServerTime.getServerDate() + ".jpg";
File file = new File(saveImgDirectory + File.separator + image);
try {
if (data == null) {
Toast.makeText(context, "IMAGE NOT SAVED", Toast.LENGTH_LONG).show();
bblockScenario();
Log.d("CAMPROBLEM", "NULL DATA");
return;
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
FileOutputStream out = null;
out = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.PNG, 90, out);
if (out != null) {
out.close();
}
} catch (Exception e) {
Toast.makeText(context, "IMAGE NOT SAVED", Toast.LENGTH_LONG).show();
bblockScenario();
Log.d("CAMPROBLEM", "E", e);
return;
} finally {
try {
} catch (Throwable ignore) {
}
}
Toast.makeText(context, "IMAGE SAVED", Toast.LENGTH_LONG).show();
return;
} catch (Exception ex) {
Log.d("CAMPROBLEM", "bblockScenario", ex);
}
}
Here in onActivityResult i get null data on every 3th picture. Cant figure why.
I have all the premision in my manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false"/>
Any help and knowledge of this problem will make my life easier. Hope that someone can help me.
Thanks in advance
EDIT:
Logcat:
05-23 10:26:17.412: E/AndroidRuntime(14022): FATAL EXCEPTION: main
05-23 10:26:17.412: E/AndroidRuntime(14022): java.lang.IllegalArgumentException: View not attached to window manager
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:671)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:364)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.view.WindowManagerImpl$CompatModeWrapper.removeView(WindowManagerImpl.java:163)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.app.Dialog.dismissDialog(Dialog.java:347)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.app.Dialog.dismiss(Dialog.java:330)
05-23 10:26:17.412: E/AndroidRuntime(14022): at es.zonsko.bitola.blocator.activity.BlocatorTabHostActivity$SyncTask.onPostExecute(BlocatorTabHostActivity.java:381)
05-23 10:26:17.412: E/AndroidRuntime(14022): at es.zonsko.bitola.blocator.activity.BlocatorTabHostActivity$SyncTask.onPostExecute(BlocatorTabHostActivity.java:1)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.os.AsyncTask.finish(AsyncTask.java:631)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.os.Looper.loop(Looper.java:153)
05-23 10:26:17.412: E/AndroidRuntime(14022): at android.app.ActivityThread.main(ActivityThread.java:5070)
05-23 10:26:17.412: E/AndroidRuntime(14022): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 10:26:17.412: E/AndroidRuntime(14022): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 10:26:17.412: E/AndroidRuntime(14022): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
05-23 10:26:17.412: E/AndroidRuntime(14022): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
05-23 10:26:17.412: E/AndroidRuntime(14022): at dalvik.system.NativeStart.main(Native Method)
You can handle this exception in onActivityResult, please use below code at start of your onActivityResult()
if(resultcode != RESULT_OK)
return;

Camera NullPointerException

Im working off the Android camera tutorial, SDK 11. For some reason I'm getting a Null Pointer within handleCameraPhoto(). The only thing I see is "Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity", but I can't sort out why.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
///Toast.makeText(this, "File Uri"+fileUri.toString(), Toast.LENGTH_LONG).show();
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
handleCameraPhoto(data);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
finish();
} else {
// Image capture failed, advise user
finish();
Toast.makeText(this, "Image capture failed, quiting", Toast.LENGTH_LONG).show();
}
}
}
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
/** 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), "Shindiggy");
// 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("Shindiggy", "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 {
return null;
}
return mediaFile;
}
Error Cat
11-19 11:39:06.782: W/dalvikvm(7719): threadid=1: thread exiting with uncaught exception (group=0x41549700)
11-19 11:39:06.782: E/AndroidRuntime(7719): FATAL EXCEPTION: main
11-19 11:39:06.782: E/AndroidRuntime(7719): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.shindiggy.shindiggy/com.shindiggy.shindiggy.CameraActivity}: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Looper.loop(Looper.java:137)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invoke(Method.java:525)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-19 11:39:06.782: E/AndroidRuntime(7719): at dalvik.system.NativeStart.main(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): Caused by: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.handleCameraPhoto(CameraActivity.java:68)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.onActivityResult(CameraActivity.java:51)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.Activity.dispatchActivityResult(Activity.java:5322)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
11-19 11:39:06.782: E/AndroidRuntime(7719): ... 11 more
It seems that handleCameraPhoto(asdf) is being called with an argument in your code (but you haven't shown us this part), and the problem is that the object asdf was not allocated with new. That means that there's no physical object in the program's memory.
So when the instructions of the method are executed, more especifically data.getData(), the crash happens because the name data doesn't refer to a valid object in your program's memory.
NullPointerException errors happen when we try to access members of an object that was not allocated properly. Make sure you allocate the object when calling handleCameraPhoto().
Sometimes when the phone is plugged into a USB cord, access to Camera files is blocked for security reasons. Also, check for null data when coming back to activity from Camera.
Thanks for the input guys, its helped me think of what I needed to look for.
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.
See onActivityResult returns null data for an Image Capture
So with that said, updated handleCameraPhoto to get the fileUri, and the app is back to working.
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
this.fileUri, Toast.LENGTH_LONG).show();
}

Android onActivityResult() returning NullPointerException on image capture

I'm having trouble with receiving the data capture from a Camera intent I have developed. I have used the code present in the android API guides. Can anyone tell where I am going wrong? I can see that the who=null and data=null parameters present in the LogCat printout are probably causing the error but I'm unsure as to why that is.
Camera Activity
//ESSENTIAL VARIABLES - DD - 29/04/2013
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
MenuItem item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_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);
}
/**
* Gets the OutputMediaFileUri and accepts media type as a parameter
* #param type
* #return
*/
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* Method taking media type as a parameter and will save images taken to a public directory on users' device.
* #param type
* #return
*/
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CrowdSnapCymru");
if(!mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("CrowdSnapCymru", "failed to create photo directory");
return null;
}
}
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{
return null;
}
return mediaFile;
}
/**
* Receives the result of Camera intent.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image saved to: \n" + data.getData() , Toast.LENGTH_LONG).show();
}
else if(resultCode == RESULT_CANCELED){
Toast.makeText(this, "User canceled the image capture", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Image capture failed. Please try again", Toast.LENGTH_LONG).show();
}
}
}
The code loads the Camera application and will produce the successful result if I cancel the application but if I accept the image or RESULT_OKAY the NullPointerException is produced.
LogCat Printout
05-01 09:57:48.894: E/AndroidRuntime(974): FATAL EXCEPTION: main
05-01 09:57:48.894: E/AndroidRuntime(974): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {rcahmw.prototype.crowdsnapcymru/rcahmw.prototype.crowdsnapcymru.SnapCamera}: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Looper.loop(Looper.java:137)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 09:57:48.894: E/AndroidRuntime(974): at dalvik.system.NativeStart.main(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): Caused by: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at rcahmw.prototype.crowdsnapcymru.SnapCamera.onActivityResult(SnapCamera.java:84)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
Any advice would be brilliant. Pretty new to using Camera application in android.
Save your fileUri variable somewhere and use it in onActivityResult instead of data.getData
Try passing Following File URI as EXTRA_OUTPUT as follow. Your onCreate would look like :
Uri picUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_camera);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
intent.putExtra( MediaStore.EXTRA_OUTPUT, picUri );
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Then onActivityResult use picUri to access image. Declare picUri as a instance variable in your activity. So it will be available in onActivityResult

"Failure delivering result" due to NPE in managedQuery on Motorola Bravo when attempting image capture. Works fine on Evo

Getting java.lang.RuntimeException: Failure delivering result ResultInfo from a NPE apparently resulting from a call in my getRealPathFromURI function.
Video capture works fine, but image capture throws the NPE. Both image and video work fine on my Evo.
03-30 09:34:25.725 D/ZoorniApp( 2509): Handling activity result. requestCode:12345 resultCode:-1
03-30 09:34:25.733 D/AndroidRuntime( 2509): Shutting down VM
03-30 09:34:25.733 W/dalvikvm( 2509): threadid=3: thread exiting with uncaught exception (group=0x4001e2e0)
03-30 09:34:25.733 E/AndroidRuntime( 2509): Uncaught handler: thread main exiting due to uncaught exception
03-30 09:34:25.741 E/AndroidRuntime( 2509): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=12345, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.mobile.zoorni/com.mobile.zoorni.ZoorniMobile}: java.lang.NullPointerException
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3433)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.access$2900(ActivityThread.java:121)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.os.Looper.loop(Looper.java:136)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.main(ActivityThread.java:4425)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at java.lang.reflect.Method.invoke(Method.java:521)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at dalvik.system.NativeStart.main(Native Method)
03-30 09:34:25.741 E/AndroidRuntime( 2509): Caused by: java.lang.NullPointerException
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.content.ContentResolver.acquireProvider(ContentResolver.java:757)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.content.ContentResolver.query(ContentResolver.java:200)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.Activity.managedQuery(Activity.java:1495)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.mobile.zoorni.ZoorniMobile.getRealPathFromURI(ZoorniMobile.java:287)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.mobile.zoorni.ZoorniMobile.onActivityResult(ZoorniMobile.java:251)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.Activity.dispatchActivityResult(Activity.java:3828)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
Here's the relevant function:
public String getRealPathFromURI(Uri contentUri) {
String column;
column = "";
if (fileType == "picture") {
column = MediaStore.Images.Media.DATA;
}
if (fileType == "video") {
column = MediaStore.Video.Media.DATA;
}
String[] proj = { column };
Cursor cursor = managedQuery(contentUri, proj, null, null, null); // here lies the exception!
int column_index = cursor.getColumnIndex( column );
if (column_index == -1) {
alert("Path missing", "Could not locate the file requested", this);
return "";
}
cursor.moveToFirst();
return cursor.getString(column_index);
}
Here's sanitized relevant code (just removed client info)
/*
* Call the camera activity for video or picture
*/
protected void startCaptureIntent(String actionCode, int requestCode, int media) {
Intent i = new Intent(actionCode);
if (media == MEDIA_VIDEO) {
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
}
startActivityForResult(i, requestCode);
}
/*
* Handle the activity result
*
* #see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//super.onActivityResult(requestCode, resultCode, intent);
Log.d("MYDEBUGGING", "Handling activity result. requestCode:" + requestCode + " resultCode:" + resultCode);
if (resultCode == Activity.RESULT_CANCELED) {
pic_upload_button.setEnabled(true);
video_upload_button.setEnabled(true);
fileType = "none";
showToast(this, "Request canceled, Touch the picture or image button to try again");
return;
}
switch (requestCode) {
case CAMERA_PIC_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
postType = requestCode;
fileType = "picture";
// Seems that this is the only way to be sure I end up with an actual file.
filePath = getRealPathFromURI(intent.getData());
if (filePath != null) {
showToast(this, "Image ready to be shared");
} else {
showToast(this, "Something went wrong. Image could not be captured.");
}
break;
default:
alert("Activity failed", "Could not create picture file", this);
}
break;
case CAMERA_VID_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
postType = requestCode;
fileType = "video";
// Seems that this is the only way to be sure I end up with a video file.
filePath = getRealPathFromURI(intent.getData());
if (filePath != null) {
showToast(this, "Video ready to be shared");
} else {
showToast(this, "Something went wrong. Video could not be captured.");
}
break;
default:
alert("Activity failed", "Could not create video file", this);
}
break;
}
}
fileType and postType are global to the class and are used to indicate to the http uploader what type of file to send. actionCode is either MediaStore.ACTION_VIDEO_CAPTURE or MediaStore.ACTION_IMAGE_CAPTURE depending on user selection.
Any thoughts?
My guess is that the contentUri or filetype values aren't correct, so the managedQuery call fails.

Categories