我正在尝试使用jetpack库中的Paging3包从我的数据库中获取信息,但由于某种原因我无法使其工作,它根本不起作用,没有抛出任何错误,我也手动完成了所有操作,任何人都可以帮助我修复问题 ? 我的房间道是
@Dao
interface ContactDao {
@Insert
fun insertAll(vararg contacts: Contact)
@Query("SELECT * FROM contact WHERE id=:id")
fun getById(id: Int): Contact?
@Query("SELECT * FROM contact WHERE number=:number")
fun getByNumber(number: String): Contact?
@Query(
"""
SELECT
contact.id,
contact.name,
contact.number,
MAX(contact_message.message_time) AS latest_message_time,
COUNT(contact_message.id) as messages_count,
contact_message.message_body as latest_message_body
FROM
contact
INNER JOIN
contact_message
ON
contact_message.contact_id = contact.id
GROUP BY
contact.id
ORDER BY
latest_message_time DESC;
"""
)
fun getAll(): List<ContactWithCount>
@Query(
"""
SELECT
contact.id,
contact.name,
contact.number,
MAX(contact_message.message_time) AS latest_message_time,
COUNT(contact_message.id) as messages_count,
contact_message.message_body as latest_message_body
FROM
contact
INNER JOIN
contact_message
ON
contact_message.contact_id = contact.id
GROUP BY
contact.id
ORDER BY
latest_message_time DESC;
"""
)
fun getAllWithPagination(): PagingSource<Int, ContactWithCount>
}
ViewModel 函数是
class SomeClass {
@ExperimentalPagingApi
fun getAllContactsPager(): Flow<PagingData<ContactWithCount>> {
return Pager(
config = PagingConfig(pageSize = 20),
) {
db.contactDao().getAllWithPagination()
}.flow.cachedIn(viewModelScope)
}
}
我的 ui 撰写代码是
@OptIn(ExperimentalPagingApi::class)
@Composable
fun ContactsList(vm: SmsViewModel = viewModel()) {
val pager = vm.getAllContactsPager().collectAsLazyPagingItems()
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(
count = pager.itemCount
) { index ->
val item = pager[index]
item?.let {
ContactBasicInfoCard(vm = vm, contactWithCount = item)
}
}
}
}
由于某种原因它没有加载任何数据
我尝试手动完成所有事情,但根本不起作用
模拟我可以通过从
;
中删除
@Query
分号来简单地解决问题
@Dao
interface ContactDao {
@Insert
fun insertAll(vararg contacts: Contact)
@Query("SELECT * FROM contact WHERE id=:id")
fun getById(id: Int): Contact?
@Query("SELECT * FROM contact WHERE number=:number")
fun getByNumber(number: String): Contact?
@Query(
"""
SELECT
contact.id,
contact.name,
contact.number,
MAX(contact_message.message_time) AS latest_message_time,
COUNT(contact_message.id) as messages_count,
contact_message.message_body as latest_message_body
FROM
contact
INNER JOIN
contact_message
ON
contact_message.contact_id = contact.id
GROUP BY
contact.id
ORDER BY
latest_message_time DESC
"""
)
fun getAll(): List<ContactWithCount>
@Query(
"""
SELECT
contact.id,
contact.name,
contact.number,
MAX(contact_message.message_time) AS latest_message_time,
COUNT(contact_message.id) as messages_count,
contact_message.message_body as latest_message_body
FROM
contact
INNER JOIN
contact_message
ON
contact_message.contact_id = contact.id
GROUP BY
contact.id
ORDER BY
latest_message_time DESC
"""
)
fun getAllWithPagination(): PagingSource<Int, ContactWithCount>
}