Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在kotlin中将主类模型的数据传递给子类模型_Android_Kotlin_Kotlin Coroutines - Fatal编程技术网

Android 如何在kotlin中将主类模型的数据传递给子类模型

Android 如何在kotlin中将主类模型的数据传递给子类模型,android,kotlin,kotlin-coroutines,Android,Kotlin,Kotlin Coroutines,我有一组来自JSON的数据。我的问题是当数据类型不匹配时,因为我有一个主模型和子模型 这是我的JSON { "events": [ { "idEvent": "1117445", "idSoccerXML": null, "idAPIfootball": "699489", "strEvent&q

我有一组来自JSON的数据。我的问题是当数据类型不匹配时,因为我有一个主模型和子模型

这是我的JSON

{
"events": [
    {
        "idEvent": "1117445",
        "idSoccerXML": null,
        "idAPIfootball": "699489",
        "strEvent": "Suzhou Dongwu vs Liaoning Shenyang Urban",
        "strEventAlternate": "Liaoning Shenyang Urban @ Suzhou Dongwu",
        "strFilename": "China League One 2021-05-06 Suzhou Dongwu vs Liaoning Shenyang Urban",
        "strSport": "Soccer",
        "idLeague": "4628",
        "strLeague": "China League One",
        "strSeason": "2021",
        "strDescriptionEN": null,
        "strHomeTeam": "Suzhou Dongwu",
        "strAwayTeam": "Liaoning Shenyang Urban",
        "intHomeScore": "1",
        "intRound": "3",
        "intAwayScore": "0",
        "intSpectators": null,
        "strOfficial": "",
        "strHomeGoalDetails": null,
        "strHomeRedCards": null,
        "strHomeYellowCards": null,
        "strHomeLineupGoalkeeper": null,
        "strHomeLineupDefense": null,
        "strHomeLineupMidfield": null,
        "strHomeLineupForward": null,
        "strHomeLineupSubstitutes": null,
        "strHomeFormation": null,
        "strAwayRedCards": null,
        "strAwayYellowCards": null,
        "strAwayGoalDetails": null,
        "strAwayLineupGoalkeeper": null,
        "strAwayLineupDefense": null,
        "strAwayLineupMidfield": null,
        "strAwayLineupForward": null,
        "strAwayLineupSubstitutes": null,
        "strAwayFormation": null,
        "intHomeShots": null,
        "intAwayShots": null,
        "strTimestamp": "2021-05-06T07:30:00+00:00",
        "dateEvent": "2021-05-06",
        "dateEventLocal": null,
        "strTime": "07:30:00",
        "strTimeLocal": null,
        "strTVStation": null,
        "idHomeTeam": "141327",
        "idAwayTeam": "139747",
        "strResult": null,
        "strVenue": "Tazi Lake Sports Centre",
        "strCountry": "China",
        "strCity": null,
        "strPoster": "",
        "strSquare": "",
        "strFanart": null,
        "strThumb": "",
        "strBanner": "",
        "strMap": null,
        "strTweet1": null,
        "strTweet2": null,
        "strTweet3": null,
        "strVideo": null,
        "strStatus": "Match Finished",
        "strPostponed": "no",
        "strLocked": "unlocked"
    }]}
这是我的主要型号

data class LastMatch(
val events: List<Event> )
这是我的服务

interface ApiService {
@GET("eventspastleague.php?id=4628")
suspend fun getLast(): List<LastMatch>}
这是我的电脑

object RetrofitBuilder {


private fun getRetrofit1(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("https://www.thesportsdb.com/api/v1/json/1/")
        .addConverterFactory(GsonConverterFactory.create())
        .build() //Doesn't require the adapter
}


val apiService1: ApiService = getRetrofit1().create(ApiService::class.java)}
这是我的回购协议

class MainRepository(private val apiHelper: ApiHelper) {

suspend fun getLast() = apiHelper.getLast()}
这是我的ViewModel

class MainViewModel(private val mainRepository: MainRepository) : ViewModel() {

fun getLast() = liveData(Dispatchers.IO){
    emit(Resource.loading(data = null))
    try {
        emit(Resource.success(data = mainRepository.getLast()))
    }catch (exception: Exception){
        emit(Resource.error(data = null,message = exception.message ?: "Error Occured"))
    }
}}
这就是我的观点

class MatchesView : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
private lateinit var adapter: TeamAdapter
private lateinit var recyclerView: RecyclerView
private lateinit var progressBar: ProgressBar
private var arrayList: ArrayList<LastMatch>? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_matches_view)
    recyclerView = findViewById(R.id.recyclerView)
    progressBar = findViewById(R.id.progressBar)

    setupViewModel()
    setupUI()
    setupObservers()
}

private fun setupViewModel() {
    viewModel = ViewModelProviders.of(
        this,
        ViewModelFactory(ApiHelper(RetrofitBuilder.apiService1))
    ).get(MainViewModel::class.java)
}

private fun setupUI() {
    recyclerView.layoutManager = LinearLayoutManager(this)
    adapter = TeamAdapter(arrayListOf())
    recyclerView.addItemDecoration(
        DividerItemDecoration(
            recyclerView.context,
            (recyclerView.layoutManager as LinearLayoutManager).orientation
        )
    )
    recyclerView.adapter = adapter
}

private fun setupObservers() {
    viewModel.getLast().observe(this, Observer {
        it?.let { resource ->
            when (resource.status) {
                Status.SUCCESS -> {

                    recyclerView.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE
                    //This line have a error that the retrieveList is and the users is Missmatch 
                    //because is have a Main and Sub model.
                    resource.data?.let { users -> retrieveList(users)

                    }
                }
                Status.ERROR -> {
                    recyclerView.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE
                    Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
                }
                Status.LOADING -> {
                    progressBar.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                }
            }
        }
    })
}

private fun retrieveList(users: List<Event>) {
    adapter.apply {
        addUsers(users)
        notifyDataSetChanged()
    }
}}
类匹配视图:AppCompatActivity(){
私有lateinit变量viewModel:MainViewModel
私有lateinit变量适配器:TeamAdapter
私有lateinit var recyclerView:recyclerView
私有lateinit变量progressBar:progressBar
私有变量arrayList:arrayList?=null
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u匹配\u视图)
recyclerView=findViewById(R.id.recyclerView)
progressBar=findViewById(R.id.progressBar)
setupViewModel()
setupUI()
设置观察员()
}
private fun setupViewModel(){
viewModel=ViewModelProviders.of(
这
ViewModelFactory(ApiHelper(ReformationBuilder.apiService1))
).get(MainViewModel::class.java)
}
私人娱乐设置ui(){
recyclerView.layoutManager=LinearLayoutManager(此)
adapter=TeamAdapter(arrayListOf())
回收视图。附加装饰(
分割(
recyclerView.context,
(recyclerView.layoutManager作为LinearLayoutManager)。方向
)
)
recyclerView.adapter=适配器
}
私人娱乐中心(){
viewModel.getLast().observe(这个,观察者{
它?让{resource->
何时(资源状态){
Status.SUCCESS->{
recyclerView.visibility=View.VISIBLE
progressBar.visibility=View.GONE
//此行有一个错误,即RetrievelList为,而用户不匹配
//因为它有一个主模型和一个子模型。
resource.data?.let{users->retrieveList(用户)
}
}
Status.ERROR->{
recyclerView.visibility=View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,it.message,Toast.LENGTH\u LONG.show())
}
Status.LOADING->{
progressBar.visibility=View.VISIBLE
recyclerView.visibility=View.GONE
}
}
}
})
}
私人娱乐检索列表(用户:列表){
adapter.apply{
添加用户(用户)
notifyDataSetChanged()
}
}}
如何将数据从LastMatch(主模型)传递到事件(子模型)以将其显示到适配器

class MainViewModel(private val mainRepository: MainRepository) : ViewModel() {

fun getLast() = liveData(Dispatchers.IO){
    emit(Resource.loading(data = null))
    try {
        emit(Resource.success(data = mainRepository.getLast()))
    }catch (exception: Exception){
        emit(Resource.error(data = null,message = exception.message ?: "Error Occured"))
    }
}}
class MatchesView : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
private lateinit var adapter: TeamAdapter
private lateinit var recyclerView: RecyclerView
private lateinit var progressBar: ProgressBar
private var arrayList: ArrayList<LastMatch>? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_matches_view)
    recyclerView = findViewById(R.id.recyclerView)
    progressBar = findViewById(R.id.progressBar)

    setupViewModel()
    setupUI()
    setupObservers()
}

private fun setupViewModel() {
    viewModel = ViewModelProviders.of(
        this,
        ViewModelFactory(ApiHelper(RetrofitBuilder.apiService1))
    ).get(MainViewModel::class.java)
}

private fun setupUI() {
    recyclerView.layoutManager = LinearLayoutManager(this)
    adapter = TeamAdapter(arrayListOf())
    recyclerView.addItemDecoration(
        DividerItemDecoration(
            recyclerView.context,
            (recyclerView.layoutManager as LinearLayoutManager).orientation
        )
    )
    recyclerView.adapter = adapter
}

private fun setupObservers() {
    viewModel.getLast().observe(this, Observer {
        it?.let { resource ->
            when (resource.status) {
                Status.SUCCESS -> {

                    recyclerView.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE
                    //This line have a error that the retrieveList is and the users is Missmatch 
                    //because is have a Main and Sub model.
                    resource.data?.let { users -> retrieveList(users)

                    }
                }
                Status.ERROR -> {
                    recyclerView.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE
                    Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
                }
                Status.LOADING -> {
                    progressBar.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                }
            }
        }
    })
}

private fun retrieveList(users: List<Event>) {
    adapter.apply {
        addUsers(users)
        notifyDataSetChanged()
    }
}}