【问题标题】:How to store image from url in Room database (Java)如何将来自 url 的图像存储在 Room 数据库中(Java)
【发布时间】:2020-04-16 16:29:35
【问题描述】:

我正在对 Room 数据库进行整个 API 响应以进行离线访问。 我已设法存储所有字符串值,但我也想将图像(获取图像 url 作为响应)存储到数据库中。 由于我没有使用 Room 数据库的经验,我对如何存储图像 int Room db 列感到困惑 以下是 API 响应

{
"beast": [{
        "id": "1",
        "name": "The Griffin of Edward III",
        "description": "The English Beast has always been a lion",
        "image": "www.google.com/uploads/beast-images/2.png"
    },
    {
        "id": "2",
        "name": "The Lion of England",
        "description": "The English Beast has always been a lion",
        "image": "www.google.com/uploads/beast-images/2.png"
    }]
}

【问题讨论】:

标签: android android-room


【解决方案1】:

您应该使用 BLOB 数据类型来存储图像。只需使用 @ColumnInfo(typeAffinity = ColumnInfo.BLOB) 注释 Room 模型类中的图像字段。观看此answer 了解更多信息。

【讨论】:

  • 获取 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期 BEGIN_ARRAY 但在第 1 行第 2104 列路径 $.beastData[0].image 错误
  • @VinodPatil 添加一些代码,导致此异常
【解决方案2】:

您可以将图像作为 blob 类型存储在房间数据库中。 您应该将图像转换为字节数组并保存。 示例:

@ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB)
private byte[] image;

【讨论】:

  • 得到 JsonSyntaxException,预期 BEGIN_ARRAY 但在第 1 行第 1 列第 2104 列路径 $.beastData[0].image
猜你喜欢
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多