在Android 11中,当你尝试从最近使用的文件夹中选择PDF文件时遇到NullPointerException: Uri
错误,这通常是由于URI处理不当或权限问题引起的。以下是解决这个问题的详细步骤和原因分析:
在Android 11中,需要显式请求存储权限。可以在AndroidManifest.xml
中添加以下权限声明:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
然后在代码中请求权限:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
}
确保URI不为空且格式正确。可以在获取URI后进行检查:
Uri selectedUri = data.getData();
if (selectedUri != null) {
// 处理URI
} else {
Log.e("URI Error", "Selected URI is null");
}
使用ContentResolver
来解析URI并读取文件内容:
try {
ContentResolver contentResolver = getContentResolver();
InputStream inputStream = contentResolver.openInputStream(selectedUri);
if (inputStream != null) {
// 读取文件内容
inputStream.close();
} else {
Log.e("File Error", "Failed to open input stream");
}
} catch (IOException e) {
e.printStackTrace();
}
以下是一个完整的示例代码,展示了如何请求权限并处理URI:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
openFilePicker();
}
}
private void openFilePicker() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Uri selectedUri = data.getData();
if (selectedUri != null) {
try {
ContentResolver contentResolver = getContentResolver();
InputStream inputStream = contentResolver.openInputStream(selectedUri);
if (inputStream != null) {
// 读取文件内容
inputStream.close();
} else {
Log.e("File Error", "Failed to open input stream");
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("URI Error", "Selected URI is null");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openFilePicker();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
通过以上步骤,你应该能够解决在Android 11中选择PDF文件时出现的NullPointerException: Uri
错误。
领取专属 10元无门槛券
手把手带您无忧上云