因此,继上一个问题之后,我进行了一些更正,以调用实际对象,而不是将其作为列表调用,但现在我出现了一个新错误。
E/VM: Index: 0, Size: 0
这来自视图模型。我假设没有项目进入列表。这意味着mapper类不起作用。这意味着数据库什么都没有。
这是接口
@Singleton
interface AnywhereAPI {
@GET(".")
suspend fun getAnyInfo(
@Query("q") query : String = "the+wire+characters&format=json",
@Query("format") format : String = "json"
): Response<GetAnyResponse>
}
回购
class AnywhereRepository @Inject constructor(
private val api: AnywhereAPI,
private val anywhereDao: AnywhereDao
){
// suspend fun getAllInfos(): DataOrException<GetAnyResponse, Boolean, Exception>{
// val response = try {
// api.getAnyInfo()
// }catch (e: Exception){
// Log.d("REPO", "getAllInfos: $e")
// return DataOrException(e = e)
// }
// Log.d("REPO INSIDE", "getAllInfos: $response")
// return DataOrException(data = response)
// }
val feeds: Flow<List<AnywhereListEntity>>
get() = anywhereDao.getInfo()
suspend fun anywhereInfo(): List<AnywhereListEntity>? {
val request = api.getAnyInfo()
if (request.isSuccessful){
val anyItems = request.body()!!.let {
AnywhereMapper.buildFrom(it)
}
anywhereDao.insertInfo(listOf(anyItems))
return (listOf(anyItems))
}
return null
}
}
ViewModel
@HiltViewModel
class AnyViewModel @Inject constructor(
private val repository: AnywhereRepository
): ViewModel() {
val anyInfoResults = repository.feeds
init {
getAnyList()
}
private fun getAnyList(){
viewModelScope.launch {
try {
repository.anywhereInfo()
}catch (e: Exception){
Log.e("VM",e.message, e.cause)
}
}
}
}
主屏幕
@Composable
fun MainScreen(anyViewModel: AnyViewModel = hiltViewModel()){
val allItems by anyViewModel.anyInfoResults.collectAsState(initial = emptyList())
Surface(modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.primary
) {
AnyList(list = allItems)
}
}
@Composable
fun AnyList(list: List<AnywhereListEntity>) {
LazyColumn{
items(list){item ->
AnyCard(anyItems = item)
}
}
}
@Composable
fun AnyCard(anyItems: AnywhereListEntity) {
Card (modifier = Modifier
.fillMaxWidth()
.height(110.dp)
.padding(16.dp),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = MaterialTheme.colors.primaryVariant,
elevation = 11.dp
) {
Row(horizontalArrangement = Arrangement.Center) {
Text(text = anyItems.name)
}
}
}
不知道如何获得我需要保存在数据库中的信息,但任何帮助都将不胜感激。我将在这里留下我更新的GitHub项目链接和API的URL。非常感谢。
GitHub链接:https://github.com/OEThe11/AnywhereCE
API链接:http://api.duckduckgo.com/?q=the+有线+字符&format=json
您传递的搜索(查询(字符串不正确。代替
@Query("q") query : String = "the+wire+characters&format=json",
应该是
@Query("q") query : String = "the wire characters",