繁体   English   中英

Room DAO 无法从数据库检索数据

[英]Room DAO fails to retrieve data from Database

我有一个“联系人”表和一个“电话号码”表。 包含电话号码的表格中有一行指向联系人自动生成的 ID。 我尝试在我的 PhoneNumbersDao 中检索链接到该联系人的所有电话号码,如下所示:

@Dao
public interface PhoneNumberDao {

    @Insert
    void insert(PhoneNumber phoneNumber);

    @Update
    void update(PhoneNumber phoneNumber);

    @Delete
    void delete(PhoneNumber phoneNumber);


    // Retrieve entry/entries by contact ID
    @Query("SELECT * FROM phone_numbers_table WHERE contact_id =:contactId")
    LiveData<List<PhoneNumber>> getPhoneNumbersById(long contactId);
}

我的电话号码 class:

@Entity(tableName = "phone_numbers_table")
public class PhoneNumber implements Serializable {

    @PrimaryKey(autoGenerate = true)
    public int id;
    /** String resource ID for the phone number */
    @SerializedName("phone_number")
    public String mPhoneNumber;
    /** String resource ID for the phone number type */
    @SerializedName("phone_number_type")
    public String mPhoneNumberType;
    /** String resource ID for the respective contact ID */
    @SerializedName("contact_id")
    @ColumnInfo(name = "contact_id")
    public int contactId;

    public PhoneNumber(String phoneNumber, String phoneNumberType, int contactId) {
        this.mPhoneNumber = phoneNumber;
        this.mPhoneNumberType = phoneNumberType;
        this.contactId = contactId;
    }

    public int getId() {
        return id;
    }

    public String getPhoneNumber() {
        return mPhoneNumber;
    }

    public String getPhoneNumberType() {
        return mPhoneNumberType;
    }

    public int getContactId() {
        return contactId;
    }
}

最后,我尝试在 PhoneNumberRepository 中使用此方法访问数据库:

public LiveData<List<PhoneNumber>> getPhoneNumbersByContactId(long id) {
        return phoneNumberDao.getPhoneNumbersById(id);
    }

但是该方法仍然返回 null。为什么会这样呢?

通过这个观察者将这个观察者添加到你的片段活动中,如果你在数据库中有数据,你将能够从数据库中获取数据,否则你将得到null

 viewModel.getPhoneNumbersByContactId(contactId).observe(this, new Observer<List<PhoneNumber>>() {
      @Override
      public void onChanged(@Nullable List<PhoneNumber> phoneList) {
//Here you will get all your phone list if you have any in database else you will get null
      }
  });

您的 PhoneNumber class 中应该有两个构造函数,一个接受 id,另一个没有它并带有忽略注释。也许这就是数据未保存在数据库中的原因。 所以你的代码应该像

@Ignore
 public PhoneNumber(String phoneNumber, String phoneNumberType, int contactId) {
    this.mPhoneNumber = phoneNumber;
    this.mPhoneNumberType = phoneNumberType;
    this.contactId = contactId;
}

 public PhoneNumber(int id, String phoneNumber, String phoneNumberType, int contactId) {
    this.id = id;
    this.mPhoneNumber = phoneNumber;
    this.mPhoneNumberType = phoneNumberType;
    this.contactId = contactId;
}

房间需要默认构造函数。 因此,在您的实体中创建默认构造函数。

 public PhoneNumber() {
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM