java - 尝试从图库中获取图像时应用程序崩溃。请查看详情

标签 java android uri android-bitmap bitmapfactory

我已经设置了代码,允许我从图库中获取图像并将其显示在 ImageView 中。 我的代码在 Android 版本 5.0.2 上运行,但在低于该版本的 Android 版本上崩溃。

这是我收到的错误:由以下原因引起:java.lang.NullPointerException:尝试在 com. humanehelper. humanehelper.PostARequest.getResizedBitmap(PostARequest.java:353) 处的空对象引用上调用虚拟方法“int android.graphics.Bitmap.getWidth()”

这是 PostARequest.java 文件的代码:

public class PostARequest extends Fragment {

    Bitmap bitmap;
    ImageView hPic;
    ProgressBar progressBar;

    private OnFragmentInteractionListener mListener;

    public PostARequest() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_post_a_request, container, false);

        progressBar = (ProgressBar) rootView.findViewById(R.id.pbHeaderProgress);

        hPic = (ImageView) rootView.findViewById(R.id.h_pic);
        hPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
                builder.setItems(R.array.choose_profile_pic_choices, mDialogListener);
                android.app.AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        return rootView;
    }

    protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int position) {
            switch (position) {
                case 0: // Take picture
                    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                    break;
                case 1: // Choose picture
                    Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    choosePhotoIntent.setType("image/*");
                    startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
                    break;
            }
        }
    };

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

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
                if (data == null) {
                    // display an error
                    return;
                }
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                bitmap = BitmapFactory.decodeFile(picturePath);
                Bitmap convertedImage = getResizedBitmap(bitmap, 200);
                hPic.setImageBitmap(convertedImage);
            }

        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(getContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
        }

    }

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float)width / (float) height;
        if (bitmapRatio > 0) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

我不知道这里出了什么问题。

请告诉我。

请配合问题的格式问题,我仍处于学习阶段。

最佳答案

Intent galleryIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

    }

关于java - 尝试从图库中获取图像时应用程序崩溃。请查看详情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735506/

相关文章:

http - jdk.incubator.httpclient URI 查询字符串在包含编码的保留字符时被截断

java - Spring @Autowired 在 Maven Surefire 插件中生成线程时返回 null

android - Android Studio 主密码是什么?

php - PHP文件的真实URI?

java - 在 Android 上的 CalendarView 中触摸选定日期时无法生成事件

android - getArrayLength() 返回一个巨大的数字......

android - 如何检测传出铃声的结束?

java - 通过jsp从另一个网页调用一个网页

java - 同步适配器类中的单例对象

java - Applet:Java.lang.SecurityException:类 "..."的签名者信息与同一包中其他类的歌手信息不匹配