Android getContentResolver().query 获取文件路径NullPointerException
针对Android 6.0系统测试如下:
@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的形式发生变化,此时如果要获取图像的路径,可以按照如下实现:
@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();
}
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/11/android-getcontentresolver-query-get-file-path-nullpointerexception/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Android getContentResolver().query 获取文件路径NullPointerException
针对Android 6.0系统测试如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(……
文章目录
关闭
共有 0 条评论