Android Studio替换onActivityResult后CursorLoader报错如何解决
问题原因
你当前遇到的报错核心是匿名内部类的this指向优先级:在ActivityResultCallback匿名内部类中直接使用this,指向的是当前回调类实例,而非外层的Activity/Fragment上下文,所以和CursorLoader构造方法要求的Context类型不匹配。
修复方案
场景1:代码写在Activity中
直接用你的Activity类名.this替换构造CursorLoader时的this即可,比如你的Activity名为MainActivity,修改后的完整代码如下:
ActivityResultLauncher<Intent> startActivityResult = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if(result.getResultCode() == Activity.RESULT_OK) { Intent data = result.getData(); // 增加空判断避免崩溃 if (data == null || data.getData() == null) { return; } String[] proj = {MediaStore.Images.Media.DATA}; // 替换为你实际的Activity类名即可 CursorLoader cursorLoader = new CursorLoader(MainActivity.this, data.getData(), proj, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String photoPath = cursor.getString(column_index); // 用完关闭游标避免内存泄漏 cursor.close(); // 后续处理图片的逻辑 } } } );
场景2:代码写在Fragment中
调用requireContext()获取上下文即可,CursorLoader构造部分修改为:
CursorLoader cursorLoader = new CursorLoader(requireContext(), data.getData(), proj, null, null, null);
额外注意事项
Android 10(API 29)及以上版本中MediaStore.Images.Media.DATA已经被官方废弃,如果你需要适配高版本系统,建议直接通过返回的Uri访问图片资源,不要依赖绝对路径处理图片。
内容的提问来源于stack exchange,提问作者Ally
相关产品推荐
相关产品推荐

