I am using this tutorial / code to learn the camera functions: cam tutorial.
The app is crashing after the camera Intent takes the picture and returns to onActivityResult
. But I am checking the make sure data is not null:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("***** inside onActivityResult");
if (requestCode == TAKE_PICTURE) {
if (data != null) {
System.out.println("***** inside data !=null if");
imageid = data.getData().getLastPathSegment(); //returns full pic id
System.out.println("***** imageid:" + imageid);
[...]
I get inside the data != null
if statement and it crashes when I imageid = data.getData().getLastPathSegment();
.
Logcat:
01-20 12:45:02.678: ERROR/AndroidRuntime(1626): FATAL EXCEPTION: main 01-20 12:45:02.678: ERROR/AndroidRuntime(1626): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline开发者_如何学运维-data (has extras) }} to activity {org.kimile/org.kimile.Camera}: java.lang.NullPointerException 01-20 12:45:02.678: ERROR/AndroidRuntime(1626): at android.app.ActivityThread.deliverResults(ActivityThread.java:3515) 01-20 12:45:02.678: ERROR/AndroidRuntime(1626): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557) 01-20 12:45:02.678: ERROR/AndroidRuntime(1626): at android.app.ActivityThread.access$2800(ActivityThread.java:125) 01-20 12:45:02.678: ERROR/AndroidRuntime(1626): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
I can't figure out why its throwing the null exception even know I am checking to make sure its not null.
Your code is throwing a NullPointerException because the object returned from data.getData()
is null. Thus when you call getData().getLastPathSegment()
, the method getLastPathSegment()
is being called on a null object - giving you your NPE.
Like willytate said, if you want to avoid the problem all together make sure you check the value of resultCode
. Otherwise, make sure you check if getData()
is null as well.
Well, if data
is not null, data.getData()
can still be null, and you can't call getLastPathSegment()
on null. Maybe check that first, and if that's the case, maybe as @willytate commented, there is something wrong with the returned data?
Check for the resultCode and requestCode avoiding them if null
if (resultCode == RESULT_OK && data != null)
On returning after capturing image using camera intent sometimes it does not returns us data so that you have to use
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get(TAG_data);
精彩评论