簡體   English   中英

Android 使用相機意圖捕獲圖像后應用程序崩潰

[英]Android App crashes after capturing image using camera intent

該應用程序嘗試使用設備的攝像頭捕獲圖像並將其上傳到 FireBase。 但是,在捕獲圖像后,應用程序會崩潰。

It shows the error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference

MainActivity 中的函數:

 private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        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 e) {
                Log.e("MainActivity", "Error creating file", e);
            }
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

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

        storage = FirebaseStorage.getInstance().getReference();
        take_pic = (Button) findViewById(R.id.take_pic);
        imageView = (ImageView) findViewById(R.id.pic_view);

        progressDialog = new ProgressDialog(this);

        take_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();

            }
        });
    }

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

        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            progressDialog.setMessage("Uploading...");
            progressDialog.show();
            StorageReference filepath;

            Uri uri = data.getData();

            filepath = storage.child("Photos").child(uri.getLastPathSegment());

            filepath.putFile(photoURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

您收到該錯誤是因為您的 intent.getData 是 null。 它也發生在我身上,你在使用拍照意圖時的 onActivityResult 總是將數據作為 null。 作為一種解決方法,我將 photoURI 設置為活動中的全局變量,然后 onActivityResult 再次調用它。 它會是這樣的:

首先你聲明變量

Uri myPhotoUri = null;

然后,在 dispatchTakePictureIntent function 中啟動它:

private void dispatchTakePictureIntent() {
    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 e) {
            Log.e("MainActivity", "Error creating file", e);
        }
        if (photoFile != null) {

            //you are adding initializing the uri
            myPhotoUri = FileProvider.getUriForFile(this,
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
        }
    }
}

在您的 onActivityResult 上,您使用該 uri 調用您的 firebase function。 它現在將具有上傳所需的信息:

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

    if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        StorageReference filepath;

      //you delete the Uri uri = data.getData();
        filepath = storage.child("Photos").child(uri.getLastPathSegment());

        //here you call it

        filepath.putFile(myPhotoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

首先檢查您是否有使用相機的權限,然后

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);

然后onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQ && resultCode == Activity.RESULT_OK) {
        bitmap = (Bitmap) data.getExtras().get("data");
        Bitmap.createScaledBitmap(bitmap, 150, 150, true);
    }
}

然后從 bitmap 到 byte[]

public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
        if(bitmap == null) return null;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);

        return byteArrayOutputStream.toByteArray();
    }

你現在可以用 bitmap 或 byte[] 做任何你想做的事

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM