Активность становится пустой в методе onActivityResult - PullRequest
0 голосов
/ 31 октября 2019

Когда пользователь нажимает кнопку, я запускаю камеру, пользователь захватывает изображение и нажимает ок, и приложение получает сбой на устройстве с леденцом на палочке.

Отлично работает на других устройствах.

Когда я проверяю, все переменные и все в активности становится нулевым, когда пользователь возвращается после захвата изображения. Я не знаю, почему 2 младших устройства lollipop обнуляют все переменные.

Это мой код.

public void launchCamera(){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (getPermissions(Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE)) {
        openCamera();
        }
    }else{
        openCamera();
    }
}

public void openCamera(){

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }

        if (photoFile != null) {
            String authorities = getApplicationContext().getPackageName() + ".fileprovider";
            photoURI = FileProvider.getUriForFile(this,
                    authorities,
                    photoFile);
            try{
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, 1);

            }catch (Exception ex){
                Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
                ex.printStackTrace();
            }
        }
    }
}

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;
}

Logcat

java.lang.RuntimeException: Unable to resume activity {com.app.myapp/com.app.myapp}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.app.myapp}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference



Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.app.myapp}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference

РЕДАКТИРОВАТЬ

   @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {


        switch(requestCode) {
            case CAMERA_RESULT:
                if (responseCode == RESULT_OK) {
                    onProfilePicAddedFromCamera(photoURI, mCurrentPhotoPath);
                }

                break;
            case GALLERY_RESULT:
                if (responseCode == RESULT_OK) {
                    Uri selectedImage = intent.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                        onProfilePicAddedFromGallery(bitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
                break;
        }


        mTwitterAuthClient.onActivityResult(requestCode, responseCode, intent);
        callbackManager.onActivityResult(requestCode, responseCode, intent);
    }

1 Ответ

0 голосов
/ 31 октября 2019

попробуйте добавить это

public void launchCamera(){
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)     != PackageManager.PERMISSION_GRANTED) {
     if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)      context, Manifest.permission.CAMERA)) {

      //Show permission dialog
     } else {

        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.CAMERA}, code);
    }
}
    else
        openCamera();
}

и в requestPermission Method

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Log.e("", "Permission denied");
            }
        }
    }
}
...