我正在创建一个Android应用程序来跟踪财务支出,我希望允许用户批量地将金融交易导入到我的应用程序中。事务将以..csv/..txt文件的形式出现。
然而,我得到了一个神秘的例外:
抽象方法“android.content.ContentResolver.acquireUnstableProvider(android.content.Context,java.lang.String”在android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1780) at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1394) at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1247) at android.content.ContentResolver.openInputStream(ContentResolver.java:967) .
工作流程如下:用户选择文本文件导入,App内容。
启动文件选择器:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
//intent.addCategory("CATEGORY_OPENABLE");
startActivityForResult(intent, REEQUEST_CODE_IMPORT);捕捉结果:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REEQUEST_CODE_IMPORT) {
// Make sure the request was successful
Uri path = data.getData();
if (resultCode == RESULT_OK && path != null) {
InputStream inputStream = null;
try {
ContentResolver contentResolver = new ContentResolver(getContext()) {};
// Error happens in the next line
inputStream = contentResolver.openInputStream(path);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = br.readLine()) != null) {
// Do something meaningful...
}
} catch () {
// Catch the exceptions ( I have removed some boiler plate code here...)
} finally {
// Close the path ( I have removed some boiler plate code here...)
inputStream.close();
}
}
}
}发布于 2019-12-22 21:09:28
Android文档帮助我解决了这个问题:从共享存储输入流访问文档和其他文件
以下代码调整工作正在进行:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REEQUEST_CODE_IMPORT) {
// Make sure the request was successful
Uri path = data.getData();
if (resultCode == RESULT_OK && path != null) {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = getActivity().getContentResolver().openInputStream(path);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
Log.d(TAG, line);
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String content = stringBuilder.toString();
// Do something with it
}
}
}https://stackoverflow.com/questions/59444888
复制相似问题