我在使用Android中的文件选取器从外部存储中选择图像文件时遇到问题。这个问题是这个问题的结果 - No such file or diectory error in image file upload using Retrofit in Android。我的问题是从活动结果的外部存储打开和读取文件。我想将结果URI转换为文件。如何使用Android中的文件选取器从外部存储中选择文件
,我读了下载文件夹中PDF文件上的活动结果
Uri bookUri = data.getData();
if(bookUri!=null)
{
String filePath = bookUri.toString();//bookUri.toString()
String mime = app.getMimeType(filePath);
if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
{
bookFile = new File(bookUri.getPath());
ivBookFile.setImageResource(R.drawable.book_selected);
}
else{
Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
}
}
正如你可以看到我用新的文件(bookUri.getPath());转换成文件。上面的代码运行良好。这是工作。现在的问题是我试图在活动结果的DCIM/Camera文件夹中打开一个图像文件。
这是我用
Uri selectedImageUri = data.getData();
if(selectedImageUri!=null)
{
try{
bmpCoverImage = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
imageFile = new File(selectedImageUri.getPath());
if(bmpCoverImage!=null)
{
ivCoverImage.setImageBitmap(bmpCoverImage);
}
}
catch (IOException e)
{
Toast.makeText(getBaseContext(),"An error occurred with the file selected",Toast.LENGTH_SHORT).show();
}
}
正如你可以看到我用新的文件(selectedImageUri.getPath())的代码;就像我在阅读pdf文件时一样。这次代码不起作用。当我像上一个问题那样操作文件时,它给了我错误。
我用这样的方式也
imageFile = new File(Environment.getExternalStorageDirectory(),selectedImageUri.getPath());
我得到了同样的错误。请如何从外部存储器正确打开图像文件?我怎样才能将选择的文件URI从外部存储转换为文件?
非常感谢。我会尝试一下。现在我得到了什么是错误的,你明确指出了我。现在我从你身上学到了很好的一课。 –
我已经试过了。我安装了一个文件选择器。它工作完美。非常感谢。 –