我是 Kotlin Jetpack Compose android 开发的新手,我一直在尝试构建一个应用程序,让您可以做笔记,并且还可以将图像与笔记一起存储在房间数据库中。问题是,当我使用以下选择器从图库中选择图像时,它们会在应用程序运行时显示,但一旦您关闭并重新启动应用程序,图像就不再加载。
但是他们的内容 uri 存储在数据库中。最初我只存储内容选择器的 Uris,如下所示:
content://media/picker/0/com.android.providers.media.photopicker/media/1001290474
房间数据库中注释的数据类
@Entity(tableName = "notes_tbl")
data class Note(
@PrimaryKey
val id: UUID = UUID.randomUUID(),
@ColumnInfo(name = "note_title")
var title: String,
@ColumnInfo(name = "note_body")
var desc: String,
@ColumnInfo(name = "note_images")
var images: List<Uri> = emptyList()
)
多照片选择器
val multiplePhotoPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickMultipleVisualMedia(),
onResult = {
uris -> uriList.value = uris
}
)
添加笔记功能(notesList包含从Room中获取的笔记列表)
fun getNote(id: String): Note {
return notesList.value.first { note -> note.id.toString() == id }
}
我还尝试使用我在此处找到的代码将我选择的图像写入存储
val saveImageToInternalStorage: (Context, Uri) -> String = {
context: Context, uri: Uri ->
val fileName = UUID.randomUUID().toString()+".jpg"
val inputStream = context.contentResolver.openInputStream(uri)
val outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE)
inputStream.use {
input ->
outputStream.use {
output ->
input?.copyTo(output)
}
}
fileName
}
它们存在于数据库中,但由于某种原因我无法显示它们。我不知道该怎么办。请忽略任何奇怪的代码,因为我尝试了网上找到的各种方法但没有奏效。
您的内容方案 uri 仅在您的应用运行或更短的时间内有效。
为了以后能够使用内容 uri,您应该在获得该 uri 时获取持久 uri 权限。