简体   繁体   English

尝试从图库中获取图像时,应用崩溃。 请查看详细信息

[英]App crashing when trying to fetch image from gallery. Please see details

I have set up code which allows me to fetch image from gallery and show it in an ImageView . 我已经设置了允许我从图库中获取图像并将其显示在ImageView My code worked on Android version 5.0.2, but is crashing on android versions below that. 我的代码在Android版本5.0.2上有效,但是在低于该版本的android版本上崩溃。

Here's the error I'm getting: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at com.humanehelper.humanehelper.PostARequest.getResizedBitmap(PostARequest.java:353) 这是我得到的错误: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at com.humanehelper.humanehelper.PostARequest.getResizedBitmap(PostARequest.java:353)

Here's PostARequest.java file's code: 这是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);
    }
}

I don't know what is wrong here. 我不知道这是怎么回事。

Please let me know. 请告诉我。

Please cooperate on bad format of the question, I'm still in learning phase. 请就问题的格式不好进行合作,我仍处于学习阶段。

So here is the trick .. Remove this line from your onactivity result code And run it . 所以这是技巧。.从您的onactivity结果代码中删除此行并运行它。

super.onActivityResult(requestCode, resultCode, data);

This above line. 这条线以上。

 @Override
        public void onActivityResult(int requestCode, int resultCode, Intent 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);
                h.setImageBitmap(convertedImage);
            }

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

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我们从图库上传图像时应用程序崩溃? - App is crashing when we upload the image from gallery? 如何旋转从相机或画廊拍摄的图像? - How rotate image taken from camera or gallery.? 当我尝试将图像保存到图库时,应用程序不断崩溃 - App keep crashing when I try to save image to gallery 如何从图库中选择的图像中获取图像 URI。 安卓 5.0.2? - How to Get Image URI from Image selected From gallery. Android 5.0.2? 无法从Facebook获取用户的个人资料图片。 请查看详细信息 - Unable to fetch user's profile picture from facebook. Please see details Android,Java,从图库中选择图像。 商店链接并稍后打开 - Android, Java, Choose image from gallery. Store link and open later 如何在应用程序启动时调用方法? 请看细节 - How to call a method only when the app has been launched? Please see details 无法将图像从一个活动发送到另一个活动。 请查看详细信息 - Failed to send image from one activity to another. Please see details 从图库中选择图片后,应用崩溃 - App Crashing After Selecting Picture From Gallery Gallery 应用程序:从 json API 获取 URL,然后从 URL 获取每个图像 - Gallery app: Fetch URLs from json API, then fetch each image from URLs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM