从android库中获取图像会导致失败传递结果

问题描述 投票:-1回答:1

我正试图从图库中获取图像并通过改造发送它。但我无法获得文件的写入路径。在搜索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;
}

这是我从gallery app返回的结果:

    @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
android image
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.