【问题标题】:Showing error while inserting User in room database在房间数据库中插入用户时显示错误
【发布时间】:2019-07-30 09:57:43
【问题描述】:

我正在制作一个应用程序,我将房间用作数据库缓存,并使用 retrofit2 从服务器获取数据并将其保存在房间数据库中,但从服务器获取数据后无法插入房间数据库。

这是它显示的一个异常:

这是我下面的 pojo 类:

@Entity(tableName = "Users")
public class User {

@NonNull
@PrimaryKey
@SerializedName("_id")
private String _id;

@ColumnInfo(name = "name")
@SerializedName("name")
@Expose
private String name;

@ColumnInfo(name = "age")
@SerializedName("age")
@Expose
private String age;

public User(){}

public User(@NonNull String _id,String name, String age) {
    this._id = _id;
    this.name = name;
    this.age = age;
}

@NonNull
public String get_id() {
    return _id;
}

public void set_id(@NonNull String _id) {
    this._id = _id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}
}

JSON 响应

[
{
    "id": "5cf68fe7b439470017236249",
    "name": "Rhea",
    "age": "2"
},
{
    "id": "5d09006696a8470cbc7c34a2",
    "name": "Don",
    "age": "10"
},
{
    "id": "5d092d9858af5d22a80858bf",
    "name": "Roman",
    "age": "30"
},
{
    "id": "5d09e9976f3bad18b8fa54a0",
    "name": "Roman",
    "age": "30"
},
{
    "id": "5d09ea2ac127bd07b4b64f6f",
    "name": "Roman",
    "age": "30"
}
]

请有人告诉我发生了什么错误。任何 hep 将不胜感激。

【问题讨论】:

  • 请发布您的 Json 响应。好像你得到 _id 是空的。
  • 我已经发布了 JSON 响应。
  • @SerializedName("_id") 更改为 @SerializedName("id")

标签: java android android-room


【解决方案1】:
chnage 

@NonNull
@PrimaryKey
@SerializedName("_id") // key does not match with response key
private String _id;


to 


@NonNull
@PrimaryKey
@SerializedName("id")
private String _id;

【讨论】:

    【解决方案2】:

    您的模型在等待“_id”时,您的 JSON 中似乎有一个名为“id”的 id 参数。尝试删除前导下划线符号。

    【讨论】:

      【解决方案3】:

      我认为您使用 retrofit2 从服务器获取数据的一个或多个用户 ID 为空,因此您无法插入本地数据库

      【讨论】:

        猜你喜欢
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 2019-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多