[英]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.