我有这个代码,允许我从SD卡中选择文件并将其上传到服务器,它在一个活动中运行良好。现在我切换到片段并使用相同的代码,但它不起作用。发生的事情是调用onActivityResult()并选择文件弹出窗口,当我选择文件时,resultCode = -1没有任何反应。我不知道如何解决这个问题。
以下是onActivityResult()的代码:
public void selectFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_SELECT_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Here ","onActivityResult");
Log.i("Here ","onActivityResult");
Log.i("resultCode ",resultCode+"");
if (resultCode == RESULT_OK) {
Log.i("Here ","onActivityResult");
if (requestCode == FILE_SELECT_CODE) {
Log.i("Here ","onActivityResult");
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
Log.i("UriString ", uriString);
File fileToUpload = new File(uriString);
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
uploadFilePath = getPath(selectedFileUri);
Log.i("Upload File Path ", uploadFilePath);
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
uploadFilePath = uriString.replace("file://", "");
Log.i("Upload File Path ", uploadFilePath);
}
}
}
}
private String getPath(Uri selectedFileUri) {
if (selectedFileUri == null)
return null;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedFileUri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return selectedFileUri.getPath();
}