Захватывать изображение с Палатой и показывать ее в ImageView

Я продолжаю шаги официальной документации: https://developer.android.com / training / для полуторной кровати / photobasics#TaskPhotoView

Я сделал совсем равно но, получаю ошибку:

java.lang. NullPointerException: Виртуальный Attempt to invoke method 'android.content.res. XmlResourceParser android.content.pm. PackageItemInfo.loadXmlMetaData (android.content.pm. PackageManager, java.lang. String)' on в null object reference java.lang. RuntimeException: Failure delivering result ResultInfo { who=null, request=1, result =-1, data=Intent { } } to activity { com.rrgt19.partyfinder/com.rrgt19.partyfinder.activity. AddActivity }: java.lang. NullPointerException: Виртуальный Attempt to invoke method 'java.lang. Object android.os. Bundle.get (java.lang. String)' on в null object reference at android.app. ActivityThread.deliverResults (ActivityThread.java:4324) at android.app. ActivityThread.handleSendResult (ActivityThread.java:4367) at android.app. ActivityThread.-wrap19 (Ункнаун Соурсе:0) at android.app. ActivityThread $H.handleMessage (ActivityThread.java:1649) at android.os. Handler.dispatchMessage (Handler.java:105) at android.os. Looper.loop (Looper.java:164)

Разрешения:




FileProvider:


           

file_paths:



    

Код:

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mPhotoImageView;

    public static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private String mCurrentPhotoPath;

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

        // Views
        mPhotoImageView = findViewById(R.id.photoImageView);

        // Listeners
        mPhotoImageView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == mPhotoImageView) {

            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {


                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            225);
                }


                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.CAMERA)) {

                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            226);
                }
            } else {
                dispatchTakePictureIntent();
            }
        }
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(AddActivity.this, "com.example.android.fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
            }
        }
    }

    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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

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

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras(); // Aquí es null
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mPhotoImageView.setImageBitmap(imageBitmap);
        }
    }
}

В настоящее время, мне удается выстрелить фотографию правильно но, когда я кликаю в OK, чтобы переходить в мой Activity, App закрывается. Я использую Андроид Ноугат 7.0 в участнике соревнования и в моем личном телефоне.

Какая-то идея?

6
задан 26.06.2019, 18:05
1 ответ

Чтобы оказываться одну вовлеченной fotogrГЎfia в ImageView APP с небольшим качеством, в mГ - он подал меня со следующим cГіdigo.

public class MainActivity extends AppCompatActivity {

static final int REQUEST_IMAGE_CAPTURE = 1;

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

//Metodo que llama el botón para tomar la imagen. No es de calidad, es para usar como iconos y poco más.
public void tomarFotografia(View v) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");                                                                   
        ImageView imageView=(ImageView)findViewById(R.id.destinoFoto);  //"destinoFoto" es el imageView seleccionad en la APP para mostrar la fotografía tomada.
        imageView.setImageBitmap(imageBitmap);
    }
}
0
ответ дан 03.12.2019, 01:08