Autoincrement字段返回null

时间:2018-06-09 14:43:43

标签: android

我正在尝试使用AsyncTask来填充我的数据库,但是每当我尝试获取其ID时,公式和婴儿的ID都为空。

private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
    private final FormulaDao dao;
    private final BabyDao babyDao;
    private final BottleDao bottleDao;

    PopulateDbAsync(ProductDatabase db) {
        dao = db.formulaDao();
        babyDao = db.babyDao();
        bottleDao = db.bottleDao();
    }

    @Override
    protected Void doInBackground(final Void... params) {
        dao.deleteAll();
        Formula a = new Formula("a");
        dao.insert(a);
        Formula b = new Formula("b");
        dao.insert(b);
        babyDao.deleteAll();
        Baby c = new Baby("John", "Doe");
        babyDao.insert(c);
        Log.v("Test", ""+c.getId());
        Bottle bottle = new Bottle("000000000000000000000006", c.getId(), a.getId());
        bottleDao.insert(bottle);
        return null;
    }
}

Baby类的定义如下:

@Entity(tableName = "baby")
public class Baby {

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private int id;

@NonNull
@ColumnInfo(name = "first")
private String fName;

@NonNull
@ColumnInfo(name = "second")
private String lName;

public Baby(@NonNull String fName, @NonNull String lName) {
    this.fName = fName;
    this.lName = lName;
}

\\ Other getters and setters not included

Formula类定义如下

@Entity(tableName = "formula")
public class Formula {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private int id;

@NonNull
@ColumnInfo(name = "name")
private String name;

public Formula(String name) {
    this.name = name;
}
\\ Other getters and setters not included

Bottle类定义如下:

@Entity(tableName = "bottle", foreignKeys = {@ForeignKey(entity = Baby.class,
                                                     parentColumns = "id",
                                                     childColumns = "babyid",
                                                     onDelete = CASCADE),
                                        @ForeignKey(entity = Formula.class,
                                                    parentColumns = "id",
                                                    childColumns = "formulaid",
                                                    onDelete = CASCADE)})
public class Bottle {

@PrimaryKey
@NonNull
@ColumnInfo(name = "id")
private String id;
@NonNull
@ColumnInfo(name = "babyid")
private int babyID;
@NonNull
@ColumnInfo(name = "formulaid")
private int formulaID;

public Bottle(String id, int babyID, int formulaID) {
    this.id = id;
    this.babyID = babyID;
    this.formulaID = formulaID;
}

1 个答案:

答案 0 :(得分:0)

你将id作为null的原因是因为你没有传递任何值,即使它是用

注释的
  

@autogenerated

你已经传递了一些价值。 最好的方法是在构造函数中使用id

public Baby(int id ,@NonNull String fName, @NonNull String lName) {
    this.fName = fName;
    this.lName = lName;
    this.id = id;
}

并在实例化对象时将一些整数值传递给id。