从棒棒糖画廊采摘图像

时间:2015-02-05 23:09:40

标签: android

我正在从画廊中挑选图片,我的代码与kitkat配合得很好但是它在棒棒糖中崩溃了。

我的代码:

    public static int LOAD_IMAGE_RESULTS = 1;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == LOAD_IMAGE_RESULTS && data != null && data.getData() != null) {
            Uri _uri = data.getData();

            //User had pick an image.
            Cursor cursor = getActivity().getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
            cursor.moveToFirst();

            //Link to the image
            final String imageFilePath = cursor.getString(0);
            Log.w("ImageFile",imageFilePath);
            cursor.close();
          }
}

我的代码崩溃,因为imageFilePath返回null。我该如何解决它?

1 个答案:

答案 0 :(得分:0)

此代码块对我有用。

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

其中RESULT_LOAD_IMAGE = 1。

然后简单地添加了onActivityResult方法:

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;

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

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

        final int width = options.outWidth;
        final int height = options.outHeight;
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        final Bitmap scaledBitmap = Bitmap.createScaledBitmap(
                BitmapFactory.decodeFile(picturePath, options), width,
                height, true);
        imageView.setImageBitmap(scaledBitmap);
    }
}