#android #kotlin #filenotfoundexception #android-fileprovider #registerforactivityresult
#Android #kotlin #исключение filenotfoundexception #android-fileprovider #registerforactivityresult
Вопрос:
Здравствуйте, я пытаюсь использовать новый AndroidX Activity Result APIs
, особенно ActivityResultContracts.TakePicture()
контракт. Я создал образец проекта для тестирования, прежде чем вводить свое реальное приложение.
MainActivity
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding?=null
private val binding get() =_binding!!
private var photoUri:Uri?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setupButtons()
setContentView(binding.root)
}
private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { isSaved ->
if (isSaved) {
binding.imageView.setImageURI(photoUri)
}
}
private fun setupButtons() {
binding.button.setOnClickListener {
photoUri = pickUri()
takePicture.launch(photoUri)
}
}
private fun pickUri(): Uri {
val path = applicationContext.getExternalFilesDir(null)?.absolutePath
val picturesFolder = File(path, "pictures")
Log.d(TAG, "pickUri: ${picturesFolder.absolutePath}")
val sdf = SimpleDateFormat("yyyyMMdd_HHmmss")
val dt = sdf.format(Date())
val fileName = "profile-picture-user-4-${dt}.jpg"
val imagePath = File(applicationContext.filesDir, "pictures")
val newFile = File(imagePath, fileName)
if (!picturesFolder.exists()){
picturesFolder.mkdirs()
Log.d(TAG, "pickUri: directoryCreated")
}
return getUriForFile(applicationContext, "com.example.resultactivitytutorial.fileprovider", newFile)
}
Чего я пытаюсь добиться: если не создано, создайте папку с именем pictures
внутри PACKAGE_NAME-> files
, чтобы сохранить изображение профиля, и сохраните снимок внутри этой папки, используя новый ActivityResultApi.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.resultactivitytutorial">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ResultActivityTutorial">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.resultactivitytutorial.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
И @xml/file_paths
файл:
<paths>
<files-path
name="pictures"
path="pictures/" />
</paths>
Проблема в том, что я получаю сообщение об ошибке:
W/ImageView: Unable to open content: content://com.example.resultactivitytutorial.fileprovider/pictures/profile-picture-user-4-20210118_132245.jpg
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Мне нужна помощь в устранении этой проблемы. Заранее спасибо!!
Комментарии:
1. if (!picturefolder.mkdirs()) { Toast (….); return;}
2.
create a folder named pictures inside PACKAGE_NAME-> files
?? Где это может быть? Пожалуйста, вместо этого укажите полный путь.3. <files-path для getFilesDir() . Не для getExternalFilesDir() .
4. В вашем коде есть как getExternalFilesDir, так и filesDir. Вы должны использовать только один.
5. Полный путь к папке, которую я хочу создать, — /storage/emulated/0/Android/data/com.example.resultactivitytutorial/files/pictures