android无法使用相机恢复活动结果

时间:2015-06-10 14:15:20

标签: android exception nullpointerexception camera onactivityresult

我使用相机时遇到问题。我拍了一张照片并将其保存在文件中。在相机的结果我将照片保存在图库和内部文件夹内。有时候我无法恢复活动nullpointer异常。

使用此代码我打开相机:

private void photoButtonClicked() {

    if (!runScreen.isAdded()) {
        return;
    }

    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();
        } catch (IOException ex) {
        }
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));

            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 = Environment

 .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    // imageFile = File.createTempFile(imageFileName, /* prefix */
    // ".jpg", /* suffix */
    // storageDir /* directory */
    // );
    imageFile = new File(storageDir, imageFileName + ".jpg");

    return imageFile;
}

这是结果上的代码:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 2 && resultCode == -1) {
        try {
            ExifInterface exif = new ExifInterface(
                    imageFile.getAbsolutePath());
            int rotation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            int rotationInDegrees = exifToDegrees(rotation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Bitmap image = decodeSampledBitmapFromResource(
                    imageFile.getAbsolutePath(), 1280, 800);
            FileOutputStream out = new FileOutputStream(
                    gpsService.getString(R.string.urlSave)
                            + gpsService.getPhotoName()
                            + gpsService.getString(R.string.jpeg));
            image.compress(Bitmap.CompressFormat.JPEG, 30, out);

            image.recycle();
            image = null;
            System.gc();
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        galleryAddPic();
    }
}

private void galleryAddPic() {
    // Intent mediaScanIntent = new Intent(
    // Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(imageFile.getAbsolutePath());
    // Uri contentUri = Uri.fromFile(f);
    // mediaScanIntent.setData(contentUri);
    // this.sendBroadcast(mediaScanIntent);

    if (new SharedSharedPreferences(this).getSaveAutomatically()) {
        ContentValues values = new ContentValues();
        values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA,
                imageFile.getAbsolutePath());
        getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                values);
    } else {
        f.delete();
    }
}

private int exifToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        return 270;
    }
    return 0;
}

public static Bitmap decodeSampledBitmapFromResource(String path,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and
        // keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

这是错误:

06-10 15:57:02.381: E/AndroidRuntime(8443): FATAL EXCEPTION: main
06-10 15:57:02.381: E/AndroidRuntime(8443): java.lang.RuntimeException: 
Unable to resume activity {cmd.run/cmd.run.run.specific.RunTabDefault}:     
java.lang.NullPointerException

06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2919)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2948)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2354)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at   
android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3877)

06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.app.ActivityThread.access$800(ActivityThread.java:159)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.os.Handler.dispatchMessage(Handler.java:99)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
android.os.Looper.loop(Looper.java:176)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at    
android.app.ActivityThread.main(ActivityThread.java:5419)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
java.lang.reflect.Method.invokeNative(Native Method)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
java.lang.reflect.Method.invoke(Method.java:525)

06-10 15:57:02.381: E/AndroidRuntime(8443):     at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run   
(ZygoteInit.java:1046)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at 
dalvik.system.NativeStart.main(Native Method)
06-10 15:57:02.381: E/AndroidRuntime(8443): Caused by: 
java.lang.NullPointerException
06-10 15:57:02.381: E/AndroidRuntime(8443):     at cmd.run.run.specific.RunTabDefault.onResume(RunTabDefault.java:430)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1209)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at android.app.Activity.performResume(Activity.java:5450)
06-10 15:57:02.381: E/AndroidRuntime(8443):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2909)
06-10 15:57:02.381: E/AndroidRuntime(8443):     ... 13 more

1 个答案:

答案 0 :(得分:0)

为什么不使用这样的东西?

要调用相机意图,请使用此按钮单击:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        ((Activity) context).startActivityForResult(intent, 1);

并且在画布使用此方法的活动中:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final ImageView uploadArea = (ImageView) attachmentDialog.findViewById(R.id.uploadArea);
        final EditText attachmentTitle = (EditText) attachmentDialog.findViewById(R.id.txtEditTitleAttach);
        Bitmap bitmap;
        if (resultCode == RESULT_OK) {
            if (requestCode == Constants.REQUEST_IMAGE_CAPTURE) {

                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions);

                    Matrix matrix = new Matrix();

                    matrix.postRotate(-90);

                    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                    byte[] attachmentBytes = byteArrayOutputStream.toByteArray();

                    attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);


                    uploadArea.setImageBitmap(rotatedBitmap);
                    attachmentTitle.setText("temp.jpeg");

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "CTSTemp" + 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();
                }
            }
}
}

我希望这会有所帮助。