当我拍照时它会关闭应用程序

时间:2016-02-02 12:59:00

标签: android

这是我的CameraActivity.java文件。当我打开相机并拍照时它说'#34;不幸的是应用程序已经停止工作"。捕获图像,当尝试在图像视图上加载图像时它已停止工作。请帮助我解决问题。

package com.example.perade2016;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.ImageView;

public class CameraActivity extends Activity {
    private static final String LOG_TAG = "error";
    ImageView imageView;
    static final int CAM_REQUEST = 1;
    Date curentTime;

 // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        verifyStoragePermissions(this);

        imageView = (ImageView)findViewById(R.id.imageView1);
        Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getFile();
        camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(camera_intent,CAM_REQUEST);

    }

    private File getFile()
    {
        curentTime = new Date();
        String root = Environment.getExternalStorageDirectory().toString();
        File folder = new File(root + "/Blue_&_Gold_Perade");
        if (!folder.mkdirs()) {
            Log.e(LOG_TAG, "Directory not created");
        }

        File image_file = new File(folder,"selfie_cam"+curentTime+".jpg");                    
        return image_file;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent         data) {
        setAndSaveImageWithOverlay(getBitmapOfSnappedImage());
        }

    public Bitmap getBitmapOfSnappedImage(){


        String root = Environment.getExternalStorageDirectory().toString();
        String path = root + "/Blue_&_Gold_Perade"+         "/selfie_cam"+curentTime+".jpg";

            File image = new File(path);
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap =         BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
            return bitmap;
        }

    public void setAndSaveImageWithOverlay(Bitmap snappedImage){
        Bitmap b = Bitmap.createBitmap(snappedImage.getWidth(),         snappedImage.getHeight(), Bitmap.Config.ARGB_8888);

        //the overlay png file from drawable folder

        if (snappedImage.getWidth() > snappedImage.getHeight()) {
            Bitmap overlay = BitmapFactory.decodeResource(getResources(),         R.drawable.overlay3);
            overlay =         Bitmap.createScaledBitmap(overlay,snappedImage.getWidth(),snappedImage.getHeight        (),false);
          //create canvas with a clean bitmap
            Canvas canvas = new Canvas(b);
            //draw the snappedImage on the canvas
            canvas.drawBitmap(snappedImage, 0, 0, new Paint());
            //draw the overlay on the canvas
            canvas.drawBitmap(overlay, 0, 0, new Paint());

            imageView.setImageBitmap(b);

            SaveImage(b);}
            else { 
            Bitmap overlay = BitmapFactory.decodeResource(getResources(),         R.drawable.overlay2);
            overlay =         Bitmap.createScaledBitmap(overlay,snappedImage.getWidth(),snappedImage.getHeight        (),false);


            //create canvas with a clean bitmap
            Canvas canvas = new Canvas(b);
            //draw the snappedImage on the canvas
            canvas.drawBitmap(snappedImage, 0, 0, new Paint());
            //draw the overlay on the canvas
            canvas.drawBitmap(overlay, 0, 0, new Paint());

            imageView.setImageBitmap(b);

            SaveImage(b);}
        }


    private void SaveImage(Bitmap finalBitmap) {

        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/Blue_&_Gold_Perade");
        myDir.mkdirs();
        String fname = "selfie_cam"+curentTime+".jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Checks if the app has permission to write to device storage
     *
     * If the app does not has permission then the user will be prompted to     grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,     Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

}

这是logcat中的错误代码。

01-31 22:05:17.939: E/AndroidRuntime(3514): FATAL EXCEPTION: main
01-31 22:05:17.939: E/AndroidRuntime(3514): java.lang.RuntimeException:         Failure delivering result ResultInfo{who=null, request=1, result=0, data=null}         to activity {com.example.perade2016/com.example.perade2016.CameraActivity}:         java.lang.NullPointerException
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.deliverResults(ActivityThread.java:3000)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.handleSendResult(ActivityThread.java:3043)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.access$1100(ActivityThread.java:127)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread$H.handleMessage(ActivityThread.java:1188)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.os.Handler.dispatchMessage(Handler.java:99)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.os.Looper.loop(Looper.java:137)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.main(ActivityThread.java:4441)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         java.lang.reflect.Method.invokeNative(Native Method)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         java.lang.reflect.Method.invoke(Method.java:511)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         dalvik.system.NativeStart.main(Native Method)
01-31 22:05:17.939: E/AndroidRuntime(3514): Caused by:             java.lang.NullPointerException
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.example.perade2016.CameraActivity.setAndSaveImageWithOverlay(CameraActivity.        java:83)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.example.perade2016.CameraActivity.onActivityResult(CameraActivity.java:67)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.Activity.dispatchActivityResult(Activity.java:4649)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.deliverResults(ActivityThread.java:2996)
01-31 22:05:17.939: E/AndroidRuntime(3514):     ... 11 more

1 个答案:

答案 0 :(得分:0)

这里有一些问题。

首先,假设您的过程将在相机应用程序位于前台时出现。这不能保证。您的流程可能会被终止。在这种情况下,curentTime将在您的新活动实例中为null。您需要在保存的实例状态Bundle中保存所需图像的路径,并从新活动实例中的同一Bundle恢复它。

其次,您在两个不同的位置生成该路径,引入了拼写错误或其他错误的可能性。创建路径一次并在两个地方使用相同的值。

第三,你没有处理那条路上没有图片的情况。这可能是因为用户选择不拍照。也可能是用户选择的相机应用程序在其ACTION_IMAGE_CAPTURE支持中有一个错误,它忽略了您的EXTRA_OUTPUT值。你需要优雅地处理这两种情况。

第四,我不建议在文件路径中使用&,因为这是一个保留字符。

第五,您试图拍摄照片而不等待用户授予您运行时权限。将您的拍照逻辑移到onRequestPermissionsResult(),只有在那里持有权限才能拍照。

此代码可能存在其他问题,但其中任何一个都可以解释您的症状。