图像意图和后按

Image intent and on back press

我制作了一个图像意图,我在其中捕获图像并将其保存在图像视图中,但我发现如果我打开相机并按下 phone 上的后退按钮,我的应用程序会关闭并出现错误。

我的意图代码:

btnImg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, 0);
    }
});

我的位图和 imageView 代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    imgBitmap = (Bitmap) data.getExtras().get("data");
    img.setImageBitmap(imgBitmap);
}

错误:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=0, data=null} to activity {gomugomu.civicalert/gomugomu.civicalert.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:5004)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:5047)
                  at android.app.ActivityThread.access00(ActivityThread.java:229)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:7331)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                  at gomugomu.civicalert.MainActivity.onActivityResult(MainActivity.java:83)
                  at android.app.Activity.dispatchActivityResult(Activity.java:7165)

第 83 行是这样的:imgBitmap = (Bitmap) data.getExtras().get("data");.

我想要当我按下后退按钮关闭相机并转到上一个 activity

当用户成功执行操作后,resultCode 将等于RESULT_OK。如果用户按下后退按钮,则 resultCode 将为 RESULT_CANCELED。所以你的代码必须这样修改。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
            imgBitmap = (Bitmap) data.getExtras().get("data");
            img.setImageBitmap(imgBitmap);
        }
    }

试试用 request code == 0

检查 resultCode==RESULT_OKdata!=null
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        if (requestCode == 0 && resultCode == RESULT_OK && data != null) {  
           imgBitmap = (Bitmap) data.getExtras().get("data");
           img.setImageBitmap(imgBitmap);
        }
    }
}