从Android Gallery获取图像会导致无法传递结果

时间:2018-09-03 19:03:26

标签: android image

我正在尝试从图库中获取图像并通过改装发送。但我无法获取文件的写入路径。 在SO中搜索后,我发现使用data.getData无法获取写入文件路径,现在我正在使用此方法来获取文件路径:

    public String getRealPathFromURI(Uri contentURI, Activity context) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = context.managedQuery(contentURI, projection, null,
            null, null);
    if (cursor == null)
        return null;
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    if (cursor.moveToFirst()) {
        String s = cursor.getString(column_index);
        // cursor.close();
        return s;
    }
    // cursor.close();
    return null;
}

这是我从图库应用返回的结果的地方:

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

        case 100 :
            if(resultCode == RESULT_OK && data != null){
                attachmentFile = new File(getRealPathFromURI(data.getData(),this));

                Toast.makeText(this,"File Explorer OK",Toast.LENGTH_SHORT).show();
            }
            else
                Toast.makeText(this,"File Explorer NOK",Toast.LENGTH_SHORT).show();
            break;
}

但是在使用此方法和类似方法后,出现此错误:

java.lang.RuntimeException: Failure delivering result     ResultInfo{who=null, request=100, result=-1, data=Intent {    dat=content://com.android.providers.media.documents/document/image:160640  flg=0x1 }} to activity  {com.x.TicketActivity}:  java.lang.NullPointerException

1 个答案:

答案 0 :(得分:0)

尝试一下:

public static String getRealPathFromURI(Context context, Uri uri) {
    String result;
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    if (cursor == null) {
        result = uri.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

2-不要忘记使用与onActivityResult()中使用的相同代码开始活动

startActivityForResult(pickerIntent, 200);

3-获取结果

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

    switch (requestCode) {
        case GALLERY_REQUEST_CODE:
            if (resultCode == RESULT_OK && data.getData() != null) {
                File file = new File(FileUtils.getRealPathFromURI(this, data.getData()));
                Log.i(TAG, "onActivityResult: File: " + file);
            } else {
                Log.i(TAG, "onActivityResult: Data is null");
            }
            break;
    }
}