Camera intent crashing my application after few pictures - java

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;

Related

Image uploading to Cloudinary Failed in Android

I am trying to upload an image to Cloudinary after clicking the image from the camera.
The camera is working fine but after clicking the image, the application is crashing again and again. Tried to debug it but not getting where I am having the error.
LOGCAT:
beginning of crash
05-03 00:29:58.243 4880-4880/com.example.maaz.taxit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.maaz.taxit, PID: 4880
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {com.example.maaz.taxit/com.example.maaz.taxit.ImageDeleteTest}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
at com.cloudinary.android.MultipartUtility.<init>(MultipartUtility.java:52)
at com.cloudinary.android.UploaderStrategy.callApi(UploaderStrategy.java:48)
at com.cloudinary.Uploader.callApi(Uploader.java:22)
at com.cloudinary.Uploader.upload(Uploader.java:55)
at com.example.maaz.taxit.ImageDeleteTest.onActivityResult(ImageDeleteTest.java:63)
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I tried to hard code the sample image URL's but still it is not working.
May be the issue is with this line
cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
public static final int TAKE_PHOTO_REQUEST = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST) {
if (resultCode == RESULT_OK) {
//File to upload to cloudinary
Toast.makeText(this, "Pakistan Zinabad", Toast.LENGTH_SHORT).show();
Map config = new HashMap();
config.put("cloud_name", "nomancloud");
config.put("api_key", "myKey");
config.put("api_secret", "mySecretApi");
Cloudinary cloudinary = new Cloudinary(config);
try {
cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
//finish();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "capturedImage";
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
return image;
}
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
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) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
}
}
}
Can you try using:
Map uploadResult = cloudinary.uploader().upload("http://res.cloudinary.com/demo/image/upload/sample.jpg", ObjectUtils.emptyMap());
And print the RuntimeException/uploadResult?
Try using the MediaManager class for android provided by Cloudinary. You will need to call the dispatch() method which will run on a background thread. Basically you are getting NetworkOnMainThread exception which means you are doing network calls on the UI thread with Android does not allow. Check the documentation, its easy.
String requestId = MediaManager.get().upload("imageFile.jpg")
.unsigned("sample_preset")
.dispatch();
A snippet from docs.
Checkout this link to learn more:
Cloudinary upload documentation page

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."));
}
}

Null Pointer Exception when passing Bitmap through Intent

I am trying to pass a BItmap[] from one activity to other using Intent.But, it is not getting passed,which in result is causing a Null Pointer Exception I guess. I am taking upto four images with the camera and storing them in a Bitmap[] ,which I am trying to pass to another activity.The logcat says the error is at line 94,which is where the passed Bitmap is used. Here's the code (only the relevant parts). Kindly help,Thanks in advance !
Take Pic.java :
the onCreateMethod:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.takepic);
initializeVar();
storeInArray(images);
}
The onActivity result for the four imageViews (which start the Camera activity) :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
photo1 = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(photo1);
} if(requestCode == 2 && resultCode == RESULT_OK) {
photo2 = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(photo2);
} if(requestCode == 3 && resultCode == RESULT_OK) {
photo3 = (Bitmap) data.getExtras().get("data");
imageView3.setImageBitmap(photo3);
} if(requestCode == 4 && resultCode == RESULT_OK) {
photo4 = (Bitmap) data.getExtras().get("data");
imageView4.setImageBitmap(photo4);
}
}
The method to store the individual bitmaps in the array :
private Bitmap[] storeInArray(Bitmap[] bitmap) {
// TODO Auto-generated method stub
if(photo1 != null){
bitmap[i]= photo1;
i++;
}if(photo2 != null){
bitmap[i]= photo2;
i++;
}if(photo3 != null){
bitmap[i]= photo3;
i++;
}if(photo4 != null){
bitmap[i]= photo4;
i++;
}
return bitmap;
}
And finally, the onClickListener for the button :
bCamEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(TakePic.this,NewEmail.class);
i.putExtra("Image",images);
startActivity(i);
}
});
And in the other Class:
extras = getIntent().getExtras();
if(extras!=null)
receive = (Bitmap[]) extras.getParcelableArray("Image");
and for the send email button :
newSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
convertEditTextToString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,"seemaswain.09#gmail.com");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,newSubject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,newContent);
newUris = new ArrayList<Uri>();
for(String file : images) {
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
newUris.add(u);
}
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, newUris);
startActivity(emailIntent);
}
});
}
public String[] BitMapToString(Bitmap bitmap[]){
int i=0;
String[] temp= new String[2000];
while(bitmap[i] !=null){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap[i].compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
temp[i]=Base64.encodeToString(b, Base64.DEFAULT);
i++;
}
return temp;
}
Finally, the logcat :
12-05 13:34:04.207: W/dalvikvm(3846): threadid=1: thread exiting with uncaught exception (group=0x40e62498)
12-05 13:34:04.207: E/test(3846): Exception
12-05 13:34:04.227: E/AndroidRuntime(3846): FATAL EXCEPTION: main
12-05 13:34:04.227: E/AndroidRuntime(3846): java.lang.NullPointerException
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.example.bethechange.NewEmail$1.onClick(NewEmail.java:94)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.view.View.performClick(View.java:4106)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.view.View$PerformClick.run(View.java:17150)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Handler.handleCallback(Handler.java:615)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Handler.dispatchMessage(Handler.java:92)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Looper.loop(Looper.java:137)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.app.ActivityThread.main(ActivityThread.java:4792)
12-05 13:34:04.227: E/AndroidRuntime(3846): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 13:34:04.227: E/AndroidRuntime(3846): at java.lang.reflect.Method.invoke(Method.java:511)
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
12-05 13:34:04.227: E/AndroidRuntime(3846): at dalvik.system.NativeStart.main(Native Method)
Do not pass bitmap array to another activity by intent.
Bitmap maybe is big file.It will cause "TransactionTooLargeException"
You have 2 ways to fix this :
1: Use a global singleton(If bitmaps are temp data not exist in files)
2: Pass bitmap file path
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
try {
photo = (Bitmap) data.getExtras().get("data");
} catch (Exception e) {
// TODO: handle exception
}
}
}

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

Android image resize after camera intent callback

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");

Categories