使用我的PhoneNumbersDao中的以下语句:
// Retrieve entry/entries by contact ID
@Query("SELECT * FROM phone_numbers_table WHERE contact_id = :contactId")
List<PhoneNumber> getPhoneNumbersById(long contactId);
如何在我的AsyncTask
中创建一个方法,以异步方式进入数据库,并检索与我传递给它的contactId
匹配的所有PhoneNumber对象?下面的代码是我到目前为止所拥有的,但我确信我应该在哪里通过contactId
:
private static class SelectPhoneNumberByIdAsyncTask extends AsyncTask<PhoneNumber, Void, Void> {
private PhoneNumberDao phoneNumberDao;
private SelectPhoneNumberByIdAsyncTask(PhoneNumberDao phoneNumberDao) {
this.phoneNumberDao = phoneNumberDao;
}
@Override
protected Void doInBackground(PhoneNumber... phoneNumbers) {
phoneNumberDao.insert(phoneNumbers[0]);
return null;
}
}
我现在呼叫observe()
,如图所示:
WorksideDatabase database = WorksideDatabase.getInstance(getApplication());
PhoneNumberDao phoneNumberDao = database.phoneNumberDao();
phoneNumberDao.getPhoneNumbersById(contactID).observe(this, PhoneNumber-> {
});
private static class SelectPhoneNumberByIdAsyncTask extends AsyncTask<PhoneNumber, Void, Void> {
private PhoneNumberDao phoneNumberDao;
private SelectPhoneNumberByIdAsyncTask(PhoneNumberDao phoneNumberDao) {
this.phoneNumberDao = phoneNumberDao;
}
@Override
protected Void doInBackground(PhoneNumber... phoneNumbers) {
phoneNumberDao.insert(phoneNumbers[0]);
return null;
}
}
这个异步应该做一件事(插入新的电话号码(,所以将类名更改为InsertPhoneNumAsyncTask为了检索电话号码,您可以使用LiveData
@Query("SELECT * FROM phone_numbers_table WHERE contact_id = :contactId")
LiveData<List<PhoneNumber>> getPhoneNumbersById(long contactId);
然后你可以像这个一样在你的活动或片段中观察它
getPhoneNumbersById(contactId).observe(this, new Observer<List<PhoneNumber>>() {
@Override
public void onChanged(@Nullable List<PhoneNumber> numbers) {
//here you access the returned numbers
}
});
检查这个希望它能帮助你