Android getContentResolver().query 获取文件路径NullPointerException

针对Android 6.0系统测试如下:

1
2
3
4
5
6
7
8
9
10
11
12
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

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

Cursor cursor = getContentResolver().query(fileUri, filePathColumn, null, null, null);
cursor.moveToFirst();
String filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
}

cursor的结果为null,查找原因,得到如下结论:

对于Android 6.0及后续版本,Uri的形式发生变化,此时如果要获取图像的路径,可以按照如下实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

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

String filePath = null;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Cursor cursor = getContentResolver().query(fileUri, filePathColumn, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
} else {
filePath = fileUri.getPath();
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :