【发布时间】:2020-10-02 02:32:01
【问题描述】:
我有一个片段应该:打开相机,显示拍摄的照片,保存 URI 路径(sqlite)并在我返回片段时再次显示该照片(获取保存的 URI 路径)
我的问题是当我尝试将保存的 URI 路径转换为位图时。 此错误发生:
FileNotFoundException: No content provider:
/external_files/Pictures/JPEG_20201001_234640_3080292023640638214.jpg (No such file or directory)
我的片段:
class TakePictureFragment : Fragment() {
private var photoURI: Uri? = null
private var imageView: ImageView? = null
private val itemId by lazy {
arguments?.getLong("ITEM_ID")
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.content_take_picture,container,false)
imageView = view.findViewById(R.id.view_show_photo)
val button: Button = view.findViewById(R.id.open_camera)
button.setOnClickListener {
openCamera()
}
return view
}
override fun onResume() {
super.onResume()
val photo = PhotoDAO.get(itemId)
if(photo != null) {
photoURI = Uri.parse(photo.photoURI)
showPhoto()
}
}
private fun openCamera() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
var photoFile: File? = null
try {
photoFile = createImageFile()
} catch (ex: IOException) {
Log.i("ERROR", "IOException")
}
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(context,
context.applicationContext.packageName + ".provider",
photoFile)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(cameraIntent, 1)
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
return File.createTempFile(imageFileName, ".jpg", storageDir)
// The shame problem happens if I return: return File(storageDir, "$imageFileName.jpg")
}
private fun showPhoto() {
val imageBitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoURI)
imageView?.setImageBitmap(imageBitmap)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == RESULT_OK) {
showPhoto()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.actionNext) {
PhotoDAO.save(itemId, photoURI?.path)
// Go to next Activity / Fragment
return true
}
return false
}
}
PS:URI 路径字符串正在从“PhotoDAO”中正确保存和获取
PS2:如果我使用Uri.fromFile(File(photo.photoURI)) 而不是Uri.parse(photo.photoURI),则错误只是“没有这样的文件或目录”
【问题讨论】:
-
您不应该保存/使用 uri.getPath() 而是 uri.toString() 然后不使用 File 类。 Uri.toString() 是您的内容方案。
-
此外,您还可以让自己更轻松地存储 photoFile.getAbsolutePath() 。然后你也可以使用 File 类。
-
当我尝试“Uri.fromFile(File(path))”时发生此错误“由:java.io.FileNotFoundException: / (Permission denied)”引起
-
不要使用 Uri。只有路径和文件。你当然应该告诉路径的价值。我们应该猜到这一切吗?
-
它适用于 asolutePath... 我稍后会在这里发布最终的工作代码。谢谢!!
标签: android android-fragments android-camera