Как получить изображение или «imagePath» через Dialog-Activity Communication? - PullRequest
0 голосов
/ 02 мая 2018

У меня ImageView открывается dialog с 2 вариантами

  1. для выбора фотографии из External Memory

  2. или возьмите новый, используя Camera

он открывает dialog и диалоговое окно успешно принимает permissions, затем открывает камеру или память

но это дает мне error, когда я выбираю фотографию из памяти или утверждаю сделанную фотографию камерой

Я использую OnPhotoReceivedListener interface в dialog fragment для получения photo и imagePath

Вот как я называю Dialog из Activity

public class EditNoteActivity extends AppCompatActivity implements ChoosePhotoDialog.OnPhotoReceivedListener{
private String mSelectedImagePath;

private static final int REQUEST_CODE = 1;

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

      mSelectedImagePath = null;

    ImageView addImageIV = (ImageView) findViewById(R.id.ivAddImage);
    addImageIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*
            Make sure all permissions have been verified before opening the dialog
             */
            for(int i = 0; i < Permissions.PERMISSIONS.length; i++){
                String[] permission = {Permissions.PERMISSIONS[i]};
                if(checkPermission(permission)){
                    if(i == Permissions.PERMISSIONS.length - 1){
                        Log.d(TAG, "onClick: opening the 'image selection dialog box'.");
                        ChoosePhotoDialog dialog = new ChoosePhotoDialog();
                        dialog.show(getSupportFragmentManager(), "ChoosePhotoDialog");
                    }
                }else{
                    verifyPermissions(permission);
                }
            }
        }
    });

/**
 * Retrieves the selected image from the bundle (coming from ChoosePhotoDialog)
 * @param bitmap
 */
@Override
public void getBitmapImage(Bitmap bitmap) {
    Log.d(TAG, "getBitmapImage: got the bitmap: " + bitmap);
    //get the bitmap from 'ChangePhotoDialog'
    if(bitmap != null) {
        compressBitmap(bitmap, 70);
        //TODO: Save Image and get It's Url
    }
}

@Override
public void getImagePath(String imagePath) {
    Log.d(TAG, "getImagePath: got the image path: " + imagePath);

    if( !imagePath.equals("")){
        imagePath = imagePath.replace(":/", "://");
        mSelectedImagePath = imagePath;
        mImgUrls += StringManipulation.imgSerialize(new String[]{imagePath, "Description"});
        initRecyclerView(mImgUrls);
    }
}

public Bitmap compressBitmap(Bitmap bitmap, int quality){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
    return bitmap;
}

и вот мой Dialog class

public class ChoosePhotoDialog extends DialogFragment {

private static final String TAG = "ChoosePhotoDialog";

public interface OnPhotoReceivedListener{
    public void getBitmapImage(Bitmap bitmap);
    public void getImagePath(String imagePath);
}

OnPhotoReceivedListener mOnPhotoReceived;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_camera_or_memory, container, false);

    //initalize the textview for starting the camera
    TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
    takePhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: starting camera.");
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
        }
    });

    //Initialize the textview for choosing an image from memory
    TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
    selectPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
        }
    });

    // Cancel button for closing the dialog
    TextView cancelDialog = (TextView) view.findViewById(R.id.tvCancelTakingPhoto);
    cancelDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: closing dialog.");
            getDialog().dismiss();
        }
    });

    return view;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
    }
}

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

    /*
    Results when taking a new image with camera
     */
    if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Log.d(TAG, "onActivityResult: done taking a picture.");

        //get the new image bitmap
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);

        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getBitmapImage(bitmap);
        getDialog().dismiss();
    }

    /*
    Results when selecting new image from phone memory
     */
    if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Uri selectedImageUri = data.getData();
        File file = new File(selectedImageUri.toString());
        Log.d(TAG, "onActivityResult: images: " + file.getPath());


        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getImagePath(file.getPath());
        getDialog().dismiss();

    }
}
}

А это ошибка

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65544, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:14786 flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }} to activity {com.ahmed_smae.everynote/com.ahmed_smae.everynote.EditNoteActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.ahmed_smae.everynote.Utils.ChoosePhotoDialog$OnPhotoReceivedListener.getImagePath(java.lang.String)' on a null object reference

Как вы думаете, проблема с interface? Как я могу решить это?

1 Ответ

0 голосов
/ 02 мая 2018

Ошибка в вашем методе On your ActivityResult. Вы обращаетесь к методу в интерфейсе нулевого объекта.

Пожалуйста, установите ваш отладчик

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
    }
}

Затем подтвердите, что getTargetFragment () работает. Поскольку я подозреваю, что это возвращает нуль или оно обнуляется в какой-то момент, прежде чем вы получите к нему доступ.

mOnPhotoReceived кажется нулевым в вашей ошибке, поэтому вам следует установить точку останова, в точке которой вы вызываете getImagePath (), и увидеть, что объект нулевой. Далее вам просто нужно посмотреть, где / как он установлен на ноль.

...