不拍照时相机崩溃

时间:2016-01-12 04:27:11

标签: android camera

我有一个简单的活动,当点击按钮时,图片被设置为ImageView。

当我打开相机并拍照时,它很好,图片被加载到ImageView。 但是如果我通过按钮打开相机应用程序,并取消(按后退按钮),则应用程序崩溃。 我想知道如何解决它。提前谢谢。

活动

    import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SituationStatusActivity extends AppCompatActivity {
ImageView imVCature_pic_first;

private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
static final int REQUEST_IMAGE_CAPTURE = 1;
String imageFilePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_situation_status);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
     imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";

    imVCature_pic_first = (ImageView) findViewById(R.id.nirPic);

    Button uploadPic = (Button) findViewById(R.id.picUploadButton);
    uploadPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {    /*************************** Camera Intent Start ************************/
            File imageFile = new File(imageFilePath);
            Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
            // Standard Intent action that can be sent to have the camera
            // application capture an image and return it.
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);   // set the image file name
            startActivityForResult(intent, 1);
            /*************************** Camera Intent End ************************/
        }
    });

}


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

    if (requestCode == 1) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}


public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}
}

LogCat错误

            java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:3688)
                                                                                   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731)
                                                                                   at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5430)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at fastner.israel.nir_zabari.onelove.SituationStatusActivity.onActivityResult(SituationStatusActivity.java:83)
                                                                                   at android.app.Activity.dispatchActivityResult(Activity.java:6299)
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:3684)
                                                                                   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731) 
                                                                                   at android.app.ActivityThread.access$1300(ActivityThread.java:162) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:135) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5430) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706) 

2 个答案:

答案 0 :(得分:2)

您需要检查resultCode以及requestCode取消相机,您将在onActivityResult

中获得空意图数据

将您的代码更改为:

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

    if (requestCode == 1 && resultCode == RESULT_OK) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}

PS:尽量避免对requestCode使用硬编码值,将其声明为常量变量。

答案 1 :(得分:0)

在onActivityResult方法中,检查requestCode后检查resultCode。如果您从相机接受图像,resultCode将返回RESULT_OK,如果您没有接受来自相机的图像,则返回RESULT_CANCEL。在您的情况下,您不接受来自摄像机的任何图像并返回活动,因此resultCode将为RESULT_CANCEL。如果您不检查resultCode的条件,则应用程序将崩溃。

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

    if (requestCode == 1) {
      if (resultCode == RESULT_OK) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
       }
       else{
            // your code in cancel condition
       }
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}