我在写一份外汇申请。接收到空数据(Json正常)。我试着调试它,但我不明白错误在哪里,是什么。如果您能帮助我了解错误或错误在哪里,我将不胜感激。下面是我的代码:
ApiService:
interface ApiService {
@GET("daily_json.js")
suspend fun getValute(): Response<Valute>
}
RetrofitInstance:
object RetrofitInstance {
private val retrofit by lazy {
Retrofit.Builder().baseUrl("https://www.cbr-xml-daily.ru/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api: ApiService by lazy {
retrofit.create(ApiService::class.java)
}
}
资料档案库:
class Repository {
suspend fun getVal(): Response<Valute>{
return RetrofitInstance.api.getValute()
}
}
视图模型:
class StartViewModel: ViewModel() {
var repo = Repository()
val moneyList: MutableLiveData<Response<Valute>> = MutableLiveData()
fun getMoney(){
viewModelScope.launch {
moneyList.value = repo.getVal()
}
}
}
片段:
class StartFragment : Fragment() {
private lateinit var _binding: FragmentStartBinding
private val binding get() = _binding!!
private val adapter = StartAdapter()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentStartBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.rvStart.adapter = adapter
val viewModel = ViewModelProvider(this).get(StartViewModel::class.java)
viewModel.getMoney()
viewModel.moneyList.observe(viewLifecycleOwner,{list ->
list.body()?.let { adapter.setList(it) }
})
}
适配器:
class StartAdapter: RecyclerView.Adapter<StartAdapter.StartHolder>() {
var listValute = emptyList<Valute>()
class StartHolder(item: View): RecyclerView.ViewHolder(item) {
val binding = ItemBinding.bind(item)
fun bind(valute: Valute) = with(binding){
nameMoney.text = valute.CharCode
purchase.text = valute.Value.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StartHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
return StartHolder(view)
}
override fun getItemCount(): Int {
return listValute.size
}
override fun onBindViewHolder(holder: StartHolder, position: Int) {
holder.bind(listValute[position])
}
fun setList(valute: Valute){
listValute = listOf(valute)
notifyDataSetChanged()
}
}
我把你可能需要的代码都附上了。
更新忘记添加DataClass
data class Valute(
val CharCode: String,
val ID: String,
val Name: String,
val Nominal: Int,
val NumCode: String,
val Previous: Double,
val Value: Double
): Serializable
1条答案
按热度按时间zyfwsgd61#
您的数据模型与从API返回的数据模型不匹配。您的
Valute
(data)类是map的一个元素(位于键“Valute”下)。所以首先为答案创建一个通用模型,例如:
在这里,在模型类中,我使用
com.google.gson.annotations.SerializedName
注解来指示在接收到的响应(JSON)中调用的字段。然后使用它(在
ApiService
中)作为来自API的响应模型:有很多网站可以从你现有的JSON创建类:
JSON结构:
