如何将我的视图模型传递给不扩展活动的类 我这样称呼我的视图模型: 在我的 EntryAbstract 类中 我哪里错了
val FrutasViewModel = ViewModelProvider.NewInstanceFactory().create(FrutasViewModel::class.java)
FrutasViewModel.frutaData.value.forEach { item->
itens.add(ShoppingCart
(id=item.id,photo=item.photo,
name=item.name,quantidade=item.quantidade
,categoria = item.categoria,descricao = item.descricao
,unidade=item.unidade,kilo = item.kilo
))
}
我的视图模型:
package com.example.quitanda.models
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class FrutasViewModel(
private val frutasServices: Services,
):ViewModel() {
private val _frutasData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow<List<ShoppingCart>>(listOf<ShoppingCart>(ShoppingCart()))
val frutaData: StateFlow<List<ShoppingCart>>
get() = _frutasData
fun getFrutas(){
viewModelScope.launch {
try {
val frutas = frutasServices.getFruta()
_frutasData.value = frutas
}catch (e:Exception){
Log.d("Service error",e.toString())
}
}
}
}
我的服务:
package com.example.quitanda.models
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
interface Services {
@GET("/category/7")
suspend fun getFruta(
//@Query("apikey")
//apikey:String = "333b4285"
): List<ShoppingCart>
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://localhost:4000/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
val frutasServices: Services = retrofit.create(Services::class.java)
我的模型:
package com.example.quitanda.models
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize
@Parcelize
data class ShoppingCart(
var count:Int=0,
@field:Json(name="product_title")
var name:String="",
@field:Json(name="product_id")
var id:Int=0,
@field:Json(name="photo_photo")
var photo:String="",
@field:Json(name="product_quant")
var quantidade:Int=0,
@field:Json(name="category_name")
var categoria:String="",
@field:Json(name="product_description")
var descricao:String="",
@field:Json(name="product_price_un")
var unidade:String="",
@field:Json(name="product_price_kg")
var kilo:String="",
var tipos:String=""): Parcelable
当我尝试运行我的代码时出现以下错误 有谁知道如何解决这个问题 谁能帮助我不胜感激
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quitanda, PID: 11031
java.lang.RuntimeException: Cannot create an instance of class com.example.quitanda.models.FrutasViewModel