【发布时间】:2017-03-30 22:39:42
【问题描述】:
我正在编写一个代码,它只为 .txt 文件创建一个文件选择器,然后在字符串中表示其内容。问题是选择一个文件后什么都没有发生(日志说结果代码是-1,请求代码是0)。谁能帮我?这是我的 .txt 文件选择器:
public void onUploadClicked(View view) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getText(R.string.select_file)), REQUEST_CODE);
}
这是我的 OnActivityResult 方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
} else {
Uri uri = data.getData();
uploadedFile = new File(uri.getPath());
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return;
}
}
这是我将 .txt 文件读入字符串的方法:
private void readFile() throws IOException {
uploadedString = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(uploadedFile));
String line;
while ((line = reader.readLine()) != null) {
uploadedString.append(line);
uploadedString.append('\n');
}
Log.i("Uploaded successfully: ", uploadedString.toString());
reader.close();
}
【问题讨论】:
-
什么是
getText(R.string.select_file)? -
对字符串资源的引用,即“选择文本文件”。
-
啊,我以为是
getString,而不是getText... 那么,您在哪里记录结果代码? (您可能还应该检查请求代码)