从图像Uri获得真正的路径不是在api 19上工作

时间:2013-11-19 08:17:23

标签: android background-image android-linearlayout

我正在尝试从Gallery设置LinearLayout背景图像。 要做到这一点,我开始图像库活动,从活动返回的URI很好但是当我将其转换为真实路径时,我在Api 19得到空值...

   public static String getRealPathFromURI(Context context, Uri contentUri) {
    String retVal = null;
    if (contentUri != null) {

        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();
        retVal = cursor.getString(column_index);
    }
    return retVal;
}

2 个答案:

答案 0 :(得分:1)

将android.permission.MANAGE_DOCUMENTS添加到清单

然后

private void showImageGallery() {
    if (Build.VERSION.SDK_INT < 19) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, GALLERY_INTENT_CALLED);
    } else {
        showKitKatGallery();
    }
}

private void showKitKatGallery(){
     Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
     intent.addCategory(Intent.CATEGORY_OPENABLE);
     intent.setType("image/*");
     startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
    mChosenImageUri = data.getData();
    final int takeFlags = data.getFlags()
            & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    // Check for the freshest data.
    getContentResolver().takePersistableUriPermission(mChosenImageUri,takeFlags);  
    }
}

答案 1 :(得分:-1)

试试这个

public static String getImgPathFromGallary(final Context context,Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = ((Activity) context).managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }