gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:27:29 27 4
gpt4 key购买 nike

我有一个“联系人”表和一个“电话号码”表。包含电话号码的表包含一行,该行指向联系人自动生成的 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);
}

我的电话号码类:

@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。为什么会这样?

最佳答案

请将此观察者添加到您的FragmentActivity中,通过此观察者,如果数据库中有数据,您将能够从数据库获取数据,否则您将得到

 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
}
});

关于java - Room DAO 无法从数据库检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61189850/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com