首页 > 解决方案 > java.lang.NullPointerException:ImageView.setImageDrawable(android.graphics.drawable.Drawable)

问题描述

我正在开发一个使用导航组件的应用程序,通过不同的片段进行导航。

在其中一个片段中,我想展示手机相机拍摄的照片,该照片是从其他片段发送的。

我的问题是当我尝试打开拍摄照片的片段时,我在该片段中收到此错误。

我添加片段的代码:

捕获片段

public class CaptureFragment extends Fragment {

    private CaptureViewModel mViewModel;
    private ImageButton btnCamara;
    private ImageView mPhotoImageView;

    public static final int REQUEST_CODE_TAKE_PHOTO = 0 /*1*/;
    private String mCurrentPhotoPath;
    private Uri photoURI;
    private EditText Ettitulo;

public static CaptureFragment newInstance() {
        return new CaptureFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {


        Ettitulo = (EditText) container.findViewById(R.id.EtInstantanea);

        mPhotoImageView = (ImageView) container.findViewById(R.id.imgCapture);
        mPhotoImageView.setImageDrawable(null);

        btnCamara = (ImageButton) container.findViewById(R.id.btnCapture);
        btnCamara.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                //1.Open the camera.

                if (v == mPhotoImageView) {

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


                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

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


                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                                Manifest.permission.CAMERA)) {

                        } else {
                            ActivityCompat.requestPermissions((Activity) getContext(),
                                    new String[]{Manifest.permission.CAMERA},
                                    226);
                        }
                    } else {
                        //Guarado de la foto en el almacenamiento interno
                        dispatchTakePictureIntent();

                    }
                }

                //2. Recover the photo and write into internal storage.
                //TODO: Use AlerrtDiolog para solicitar nombre de la foto.
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case DialogInterface.BUTTON_POSITIVE:
                                String titulo = Ettitulo.getText().toString();

                                // keep into DB.

                               Birddb bd = Birddb.getDatabase(getContext());

                                //Contructor con el titulo introducido por el usuario, y la url de la foto.

                               bd.birdDAO().insertBird(new BirdRoom(titulo, mCurrentPhotoPath));


                                //Send the Jornal,

                                Bundle bundle = new Bundle();
                                bundle.putString("edtValue", titulo);
                                bundle.putString("image", mCurrentPhotoPath);

                                //Swicth the () -> fragment
                                FragmentManager manager=getFragmentManager();
                                FragmentTransaction transaction=manager.beginTransaction();
                                JournalFragment jf = JournalFragment.newInstance();
                                jf.setArguments(bundle);
                                transaction.replace(container.getId(),jf);
                                transaction.commit();

                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                //No button clicked

                                Toast.makeText(getContext(), "Foto NO añadida a su diario personal.", Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();

                Intent intento1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File foto = new File(getActivity().getExternalFilesDir(null), mCurrentPhotoPath);
                intento1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(foto));
                startActivity(intento1);

                //3. Set the photo into the ImageView,
                Bitmap bitmap1 = BitmapFactory.decodeFile(getActivity().getExternalFilesDir(null)+"/"+Ettitulo.getText().toString());

                Drawable d = new BitmapDrawable(getResources(), bitmap1);

                mPhotoImageView.setImageDrawable(d);

                //4. Ask if the user want to keep that pjoto into his jornal.

                AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
                builder1.setMessage("¿Le gustaría guardar esta foto en su diario?");
                builder1.setCancelable(true);

                builder1.setPositiveButton(
                        "Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                //Instancio la BBDD local..
                                Birddb db = Room.databaseBuilder(getContext(),
                                        Birddb.class, "database-name").build();


                                //Añado el objeto Bird a la BBDD local.
                                BirdDAO birdDAO = db.birdDAO();
                                //List<Bird> users = userDao.getAll();
                                AsyncTask.execute(new Runnable() {
                                    @Override
                                    public void run() {

                                        //Guardar Objeto Bird en la BBDD.


                                        String descripcion = Ettitulo.getText().toString();
                                        BirdRoom bird = new BirdRoom(descripcion, mCurrentPhotoPath);
                                        Birddb.getDatabase(getContext()).birdDAO().insertBird(bird);
                                        Toast.makeText(getContext(), "Ejemplar añadido correctamente a su diario", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        });

                builder1.setNegativeButton(
                        "No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Toast.makeText(getContext(), "No se ha añadido la foto actual a su diario", Toast.LENGTH_LONG).show();
                                dialog.cancel();
                            }
                        });

                AlertDialog alert11 = builder1.create();
                alert11.show();

            }
        });


        return inflater.inflate(R.layout.fragment_capture, container, false);
    }

如果您能提供帮助,请提前感谢!

[编辑]

经过一些建议后,我更改了这样的代码,我得到了同样的错误:


        mPhotoImageView = (ImageView) container.findViewById(R.id.imgCapture);
        if(mPhotoImageView == null){
            mPhotoImageView.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.bird));
        }

标签: javaandroidandroid-fragments

解决方案


mPhotoImageView.setImageDrawable(null);

这会引发异常。将您的 Drawable 放入方法调用中。


推荐阅读