android - 捕获图像后尝试设置图像时获取 "Caused by: java.lang.NullPointerException: uri"

标签 android nullpointerexception uri picasso android-cursor

我有 2 个选项来设置图像,要么从图库中选择它,要么通过捕获它。

当用户从图库中选择图像时,它会返回一个 clang ImageView,当用户在捕获图像后尝试设置图像时,应用程序崩溃并出现以下错误:java.lang.RuntimeException: Failure delivering result ResultInfo{who= null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} 到 Activity {com.abc.xyz/com.abc.xyz.Activity}: java.lang.NullPointerException: uri

以下是我启动选择器的方式:

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_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    choosePhotoIntent.setType("image/*");
                    startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
                    break;
            }
        }
    };

下面是我如何将图像设置到 ImageView:

@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 };

                // error on the line below
                Cursor cursor = this.getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                //
                cursor.moveToFirst();

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

                Picasso.with(this)
                        .load(picturePath)
                        .into(hPic);
                hPicTag.setVisibility(View.INVISIBLE);
            }

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

    }

请告诉我这里有什么问题。

很抱歉问题的格式不正确。我在这里还是个初学者。

最佳答案

某些Android版本获取路径的方式不同。为此,我使用以下 Util 类。

public class RealPathUtil {

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API20(Context context, Uri uri){
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = { MediaStore.Images.Media.DATA };

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{ id }, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return filePath;
    }


    public static String getRealPathFromURI_API11to19(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        String result = null;

        if(Looper.myLooper() == null) {
            Looper.prepare();
        }
        CursorLoader cursorLoader = new CursorLoader(
                context,
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();

        if(cursor != null){
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
        } else {
            result = contentUri.getPath();
        }
        return result;
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index
                = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

现在根据设备的操作系统版本调用适当的方法:

if (Build.VERSION.SDK_INT < 11) {
    RealPathUtil.getRealPathFromURI_BelowAPI11(...);
} else if(Build.VERSION.SDK_INT >= 11 && <= 19) {
    RealPathUtil.getRealPathFromURI_API11to19(...);
} else if(Build.VERSION.SDK_INT > 19){
    RealPathUtil.getRealPathFromURI_API20(...);
}

关于android - 捕获图像后尝试设置图像时获取 "Caused by: java.lang.NullPointerException: uri",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589926/

相关文章:

android - 如何部署Dart Web应用程序以执行系统Shell脚本?

android - Firebase:登录前写入数据库

android - api19上的android.content.res.Resources $ NotFoundException

java - ejb注入(inject)中的NullPointerException

Android:旋转时对话框中出现 NullPointerException

java - uriBuilder 返回 http :/instead of http://

ruby-on-rails - 在 Ruby 中解析复杂的 URL

java - Android - 第二次加载文件时出现java.lang.NullPointerException

java - 如何在 Java 中使用编码 URIbuilder() 方法

java - 开发图库 View 时 setAdapter 出错